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

自古美人都是妖i 提交于 2019-11-27 03:47:40

问题


I have view which displays some data from model. I have submit button which onClick event should change model's value and I pass model's with different values but my values in TextBoxFor stay the same as they were on page load. How can I change them?


回答1:


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


来源:https://stackoverflow.com/questions/4895691/mvc-change-models-value-in-view-on-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!