MVC - 在帖子中更改模型的值

时间:2011-02-04 07:50:44

标签: asp.net-mvc asp.net-mvc-2

我有视图显示模型中的一些数据。我有提交按钮,onClick事件应该更改模型的值,我传递的模型具有不同的值,但我在TextBoxFor中的值保持与页面加载时相同。我怎样才能改变它们?

1 个答案:

答案 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);
}