问题
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