我创建了一个新的ASP.Net Core 2(Razor Pages)项目
我的模型是:
public class FormularioGenerico
{
public FormularioGenerico()
{
}
public string IP { get; set; }
public List<string> items { get; set; } = new List<string>();
}
在我放在page.cshtml.cs的页面上
public class EditarModel : PageModel
{
[BindProperty]
public FormularioGenerico ff { get; set; }
[BindProperty]
public string Message { get; set; }
public void OnGet()
{
this.ff = new FormularioGenerico();
ff.IP = "C# FORM";
ff.items.Add("OK1");
ff.items.Add("OK2");
ff.items.Add("OK3");
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var m = ModelState.IsValid; // true
Debug.WriteLine(this.ff.IP); // is Always returning null
Debug.WriteLine(this.ff.items.Count); // is Always returning null
}
}
在page.cshtml上:
@model Formulario.Pages.EditarModel
...
<h1>@Model.ff.IP</h1>
@foreach (var i in Model.ff.items)
{
<div>@i</div>
}
<button type="submit">Enviar</button>
项目输出正确 . 但完整的对象不会转到OnPost .
问题是:该模型未完全填充在OnPost上 .
How to receive the full object that was created on the OnGet, plus the changes made by the user on the form, on the post to OnPostAsync() ?
1 回答
BindProperty属性用于通知ASP.NET Core,表单提交的值应映射到指定的对象 . 在您的情况下,您设置了ff属性的值,但是您没有等效的输入值,因此ASP.NET Core将获取这些值以将它们存储回ff属性 .
为了使其工作,您将不得不用以下代码替换您的剃刀代码:
很重要 . 要使其工作,您不能使用foreach循环,因为ASP.NET核心将无法找到值 . 你将不得不使用for循环 .
我添加的输入是隐藏的,因为我猜你不希望它们可见,但你可以删除type =“hidden”,这样你就可以看到它们 . 您对这些输入所做的每个更改都将提交给OnPostAsync方法 .