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) {
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?
source share