【发布时间】:2020-09-16 10:05:01
【问题描述】:
我正在尝试在 asp.net mvc 的不同视图中重用模型。但是如果模型被传递到下一个视图并提交了新属性,那么旧的值就会丢失。
这里是我正在使用的代码示例:
型号
public class ExampleModel
{
public string Attribut1 { get; set; }
public string Attribut2 { get; set; }
}
控制器
public class HomeController : Controller
{
public IActionResult Page1()
{
return View(new ExampleModel());
}
public IActionResult Page1Check(ExampleModel model)
{
return View("Page2", model);
}
public IActionResult Page2Check(ExampleModel model)
{
return View("Page2", model);
}
}
查看1
@model Example.Models.ExampleModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<form asp-controller="Home" asp-action="Page1Check">
<label asp-for="Attribut1"></label>
<input asp-for="Attribut1" placeholder="Attribut1" />
<button type="submit">Submit</button>
</form>
视图2
@model Example.Models.ExampleModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<form asp-controller="Home" asp-action="Page2Check">
<label asp-for="Attribut2"></label>
<input asp-for="Attribut2" placeholder="Attribut2" />
<button type="submit">Submit</button>
</form>
如果我打开 Page1,则会创建一个新模型。如果在Page1中输入了attribut1并提交了Page1Check,则调用并填充了attribut1。现在模型被传递到 page2。在这里,attribut2 被填写并提交。但是,如果我检查 Page2Check 内部的模型,attribut1 为空,并且只有 attribut2 被填充。
奇怪的是,如果我在 page2 视图中检查 attribut1,它仍然存在。只有在提交之后,attribut1 才会消失。
我错过了什么,如何防止提交后填充的属性为空?
【问题讨论】:
标签: c# asp.net model-view-controller