Update the model on HttpPost and render the changes in the View

Posted by Etienne Giust on Geeks with Blogs See other posts from Geeks with Blogs or by Etienne Giust
Published on Wed, 11 Jul 2012 11:34:53 GMT Indexed on 2012/07/11 15:16 UTC
Read the original article Hit count: 361

Filed under:

 

With MVC3, I came over that problem where I was rendering a view with an updated model at the end of an HttpPost and the changes to the model were never applied to the rendered view :

 

NOT working as expected !
[HttpPost]
        public ActionResult Edit(JobModel editedJobModel)
        {
            // Update some model property
            editedJobModel.IsActive = true;
            
            // The view will NOT be updated as expected
            return View(editedJobModel);
        }

 

This is the standard behavior. In MVC3, POSTing the model does not render the Html helpers again. In my example, a HiddenFor bound to the IsActive value will not have its value set to true after the view is rendered.

 

Are you stuck, then ?

 

Well, for one, you’re not supposed to do that: in an ideal world you are supposed to apply the Post/Redirect/Get pattern. You would redirect to a new GET after your POST performed its actions. That’s what I usually do, but sometimes, when maintaining code and implementing slight changes to a pre-existing and tested logic, one prefers to keep structural changes to a minimum.

 

If you really have to (but my advice is to try to implement the PRG pattern whenever possible), here is a solution to alter values of the model on a POST and have the MVC engine render it correctly :

 

Solution
[HttpPost]
public ActionResult Edit(JobModel editedJobModel)
{
    // NOT WORKING : Update some model property
    //editedJobModel.IsActive = true;

    //Force ModelState value for IsActive property
    ModelState["IsActive"].Value = new ValueProviderResult(true, "True", null);
    
    // The view will be updated as expected
    return View(editedJobModel);
}

 

As you can see, it is a “dirty” solution, as the name (as a  string) of the updated property is used as a key of the ModelState dictionary.

Also, the use of ValueProviderResult is not that straightforward.

 

But hey, it works.

© Geeks with Blogs or respective owner