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

Cip*_*ipi 20 asp.net-mvc asp.net-mvc-2

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

Dar*_*rov 39

这就是HTML帮助程序的工作方式,它是设计的.他们将首先查看POSTed数据,然后查看模型中的数据.例如,如果你有:

<% using (Html.BeginForm()) { %>
    <%= Html.TextBoxFor(x => x.Name) %>
    <input type="submit" value="OK" />
<% } %>
Run Code Online (Sandbox Code Playgroud)

您要发布到以下操作:

[HttpPost]
public ActionResult Index(SomeModel model)
{
    model.Name = "some new name";
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

重新显示视图时,将使用旧值.一种可能的解决方法是从ModelState中删除值:

[HttpPost]
public ActionResult Index(SomeModel model)
{
    ModelState.Remove("Name");
    model.Name = "some new name";
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

  • 这对我帮助很大,谢谢!对于关闭这个问题的人:在判断这个问题是否值得之前,你需要知道这里的问题! (4认同)