我有一个简单的帖子操作,试图将新模型从post方法返回到视图。出于某些原因,当我返回新模型时,我总是看到我发布的模型,为什么会发生这种情况?我需要在post动作中更改模型的值并将它们返回给用户但是由于某种原因我无法做到这一点?
public ActionResult Build()
{
return View(new Person());
}
[HttpPost]
public ActionResult Build(Person model)
{
return View(new Person() { FirstName = "THX", LastName = "1138" });
}
这是视图代码;
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
如果我打开表格并输入“John”作为名字,输入“Smith”作为姓氏并张贴表格我得到“John”,“Smith”从后期行动中回来而不是“THX 1138”就在那里一种覆盖这种行为的方法?我也想知道它为什么这样做?
答案 0 :(得分:5)
您可以通过在帖子操作中添加this.ViewData = null;
来指示ASP.NET MVC忘记发布的值来执行此操作:
[HttpPost]
public ActionResult Build(Person model)
{
this.ViewData = null;
return View(new Person() { FirstName = "THX", LastName = "1138" });
}