ASP.NET MVC automatically binds updated model when ModelState is invalid in HttpPost

I am working on an ASP.NET MVC2 application. I realized the amazing, but amazing thing that MVC is doing behind the scenes related to ModelState and model binding. I have a ViewModel that has a whole bunch of data - some fields are part of the form and others are just part of the user interface. In HttpPost, my Action method uses DefaultModelBinder, which tries to bind the entire model, but only the fields that were part of the form are successfully deserialized - all the rest remain empty. This is beautiful and clear. If the ModelState is invalid, I need to update the model from db and bind these specific form fields before returning to the same editing view to display the ModelState validation errors associated with it.

Here, where my amazement and curiosity comes. I figured that in order to associate the form fields with the updated model, I had to call either UpdateModel() or TryUpdateModel<>() , going to the updated model. For instance:

 [HttpPost] public ActionResult EditDetail(EditDetailItemModel model) { if (model.IsValid) { // Save the results to the db return RedirectToAction(...) } // Can't simply "return View(model)". Not all fields in EditDetailItemModel // were part of the form - thus they returned null. Have to refresh // model from the db. var refreshedModel = RefreshModelFromDB(); // Is this line necessary????? TryUpdateModel<EditDetailItemModel>(refreshedModel); return View(refreshedModel); } 

But I found that if I just returned the refreshedModel to the view WITHOUT making a call to TryUpdateModel<>() , the updated model is automatically bound to the values ​​of the form fields that were submitted !! Therefore, TryUpdateModel<>() is not required here!

The only thing I can understand is that since the ModelState is in an invalid state, as soon as I returned the view with the updated model, the “MVC rendering engine” went through ModelState errors and associated these property values ​​with my updated model. It's just AWESOME! But I want to prove this assumption. I can not find documentation about this anywhere on the Internet. Can anyone confirm my hypothesis of WHY / HOW this AMAZING automatic linking is happening and / or teaching me why and how this is happening, I hope, is supported by some links to the online documentation so that I understand in more detail that going under the covers?

+4
source share
1 answer
 public ActionResult EditDetail(EditDetailItemModel model) 

This line will bind the model. Think of the ActionMethod options that are always populated with an UpdateModel call.

You do not see the refreshedModel values ​​in the view, you see the records and ModelState values ​​from the EditDetailItemModel.

0
source

All Articles