Trying to understand when model objects are instantiated in MVC3:
I have a view for editing a “Person”; each person can have multiple addresses. I’m displaying the addresses in a grid on the Person View.
This works great when displaying a person; I have a partial view which iterates through Person.Addresses and builds the table/grid.
The problem arises when creating a new person: the person object is null and the Person.Addresses reference is illegal.
I’m certain I’m missing something fairly fundamental here: since MVC will be (auto-magically) creating the new person instance upon “Save”; it would seem counter-production to try and create my own object instance, and if I did, it is unclear how I would connect it to the rest of the entry values on the form.
One last complications: the list of Addresses is optional; it is perfectly legal not to have an address at all.
As relational data is so common, there has to be a simpler solution for handling this. All clarifications appreciated!
The answer to this question is that the objects are re-constituted from the POST data in the form. This is fairly basic, but MVC hides so much of what is happening that it is hard to see when you are trying to get your (MVC) bearings.
The sequence of items is:
Notes:
When creating the page: a form is generated with fields for each part of the object being represented. MVC uses hidden fields for ID’s and other non-displayed data as well as for validation rules.
It is worth noting that forms are created (typically) either by listing all object properties on the
_CreateOrEdit.cshtmlpage:and
or by using a template for the class (templates must have the same name as the class they represent and they are located in the
Views\Shared\EditorTemplatesfolder).Using template pages is almost identical to the previous method:
and
Using the template method makes it easy to add lists (of object) to the form.
Person.cshtmlbecomes:and
MVC will handle creating as many form entries as necessary for each address in the list.
The POST works exactly in reverse; a new instance of the model object is created, calling the default parameter-less constructor, and then MVC fills in each of the fields. Lists are populating by reversing the serialization process of
@Html.EditorFor( model.List ). It is important to note that you must make certain your class creates a valid container for the list in the constructor otherwise MVC’s list re-constitution will fail:That cover’s it. There is a lot going on behind the scenes, but it is all track-able.
Two important points if you are having trouble with this:
@Html.HiddenFor(...)for everything that needs to “survive” the trip back to the server.One last point: there is a good article on dynamically adding / removing elements from a list with MVC: http://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3 It’s a good article to work through — and yes, it does work with MVC3 and Razor.