我有视图显示模型中的一些数据。我有提交按钮,onClick事件应该更改模型的值,我传递的模型具有不同的值,但我在TextBoxFor中的值保持与页面加载时相同。我怎样才能改变它们?
答案 0 :(得分:39)
这是HTML帮助程序的工作原理,它是设计的。他们将首先查看POSTed数据,然后查看模型中的数据。例如,如果你有:
<% using (Html.BeginForm()) { %>
<%= Html.TextBoxFor(x => x.Name) %>
<input type="submit" value="OK" />
<% } %>
您要发布到以下操作:
[HttpPost]
public ActionResult Index(SomeModel model)
{
model.Name = "some new name";
return View(model);
}
重新显示视图时,将使用旧值。一种可能的解决方法是从ModelState中删除值:
[HttpPost]
public ActionResult Index(SomeModel model)
{
ModelState.Remove("Name");
model.Name = "some new name";
return View(model);
}