Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 461
Cipiripi Avatar asked Feb 04 '11 07:02

Cipiripi


1 Answers

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); } 
like image 156
Darin Dimitrov Avatar answered Nov 24 '22 00:11

Darin Dimitrov