我有一个具有 2 个操作的 Controller :1 个用于显示表单,第 2 个用于处理提交的表单。像这样:
public ActionResult Create()
{
TestModel model = new TestModel() { Value1 = "aaa" };
return View(model);
}
[HttpPost]
public ActionResult Create(TestModel model)
{
model.Value2 = "bbb";
return View(model);
}
正如您所看到的,我用“aaa”预先填充了 Value1,因此它出现在表单上 - 这部分工作正常。但是,当我提交表单时,我想填充模型对象的其他属性并使用相同的 View 重新显示表单。
问题是提交时表单仍然显示原始模型对象而不是更新后的模型对象,即只有 Value1 填充了“aaa”而 Value2 为空。
我使用的 View 是通过脚手架选项自动生成的 View :
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>TestModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Value1)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Value1)
@Html.ValidationMessageFor(model => model.Value1)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Value2)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Value2)
@Html.ValidationMessageFor(model => model.Value2)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
最佳答案
您必须调用ModelState.Clear()
,这样结果才会是预期的。当 POST 数据发送回客户端时,MVC 会进行假设。但请注意,手动清除它可能会导致不良结果......
您可以在此处阅读更多信息:Asp.net MVC ModelState.Clear和 http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx
关于c# - MVC4 - 表单不显示新模型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20119507/