Archive

Posts Tagged ‘model’

How to update model data in receiving action

May 30, 2011 Leave a comment

When using all the standard out-of-the-box fuctionality of ASP.NET MVC, you may notice that you simply can’t just update a model’s properties in an action method.  Oh the code will execute just fine, but the data you see on the page will not reflect updates from code.  Here’s an example of what I mean:

[HttpPost]
public ActionResult Index(myModel m)
{
   if (ModelState.IsValid)
   {
      // do some stuff
      m.Message = "data submitted";
   }
   return View(m);
 }

The new value of m.Message will not be reflected on the page.  Instead you will see the previous value.  For the updates to be reflected you must remove the old data from Model State.  You do this in one of two ways:

  • Either clear out the affected properties, one by one using ModelState.Remove(propertyName)
  • Or just clear out the entire model state with ModelState.Clear()

So the above code becomes:

[HttpPost]
public ActionResult Index(myModel m)
{
   if (ModelState.IsValid)
   {
      // do some stuff
      ModelState.Clear()
      m.Message = "data submitted";
   }
   return View(m);
}

-Krip

P.S. credit

Categories: ASP.NET, MVC Tags: , , ,