MVC - change model's value in view on post [closed]

青春壹個敷衍的年華 提交于 2019-11-28 10:46:20

That's how HTML helpers work and it is by design. They will first look in the POSTed data and after that in the model. So for example if you have:

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

which you are posting to the following action:

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

when the view is redisplayed the old value will be used. One possible workaround is to remove the value from the ModelState:

[HttpPost]
public ActionResult Index(SomeModel model)
{
    ModelState.Remove("Name");
    model.Name = "some new name";
    return View(model);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!