ASP.NET MVC UpdateModel binding with a Hierarchy of Collections
I have the following Model design.
Template contains a list of Categories. Categories contains a List of Items.
Thus there is 3 layer hierarchy. Because the UI design requires that all 3 levels be created on 1 page, I have had to write some of my own code to get this working. It looks as follows:
I can get it to submit back to the Create Action Method and the FormCollection looks as follows.
The problem I am having is that the UpdateModel works for the Template and Category level but the Items are not populated for the C开发者_Python百科ategories. The Html looks as follows. As you can see, I have used the Category[guid_value].Items[guid_value] syntax for id. Shouldn't it figure out the binding automagically based on that?
Is there something I am missing or have to do in order to get the binding to work?
if you want your html to bind correctly to your model you have to pay some attention to html you render. The problem that i can see with your html is
<input type='hidden' value = 'Items.Index' value= 'some_guid' autocomplete = 'off'/>
with this html model binder will try to bind Items as children of Template object where it will not find any property named Items and these values will not be bound to the model. you have to change your hidden field to
<input type='hidden' name = 'Categories[category's guid].Items.Index' value = 'some guid' autocomplete = 'off'/>
and you have to just call updatemodel in your action method like
UpdateModel(yourobject);
i have not tested this code but i am more than certain that changing your html this way will get you sorted. @Mlchael Grassman you don't have to use integer based id's to bind collection anymore. plz read steve's post for more information. Actually you don't need GUID either but a random number that is unique in page's context provided that you put an extra hidden field with name index and value set to above mentioned random number. I have blogged about Master detail form in asp.net mvc using (and modifying) BeginCollectionItem method written by Steve. in part one of this blog series i simply showed how you can dynamically add fields of your detail record on client side without ajax call. In second part i brought the editor template of detail record to jquery templating engine and rendering it on client side as it would appear if rendered through ajax call.
By default MVC uses the following convention for naming.
Category[0].Items[0]
Category[0].Items[1]
Category[1].Items[0]
Category[1].Items[1]
You can include your own Update by using the following TryUpdateModel. This woud probably need some sort of loop but should get you started.
TryUpdateModel(Category[Guid].Items[Guid], "Category[Guid].Items[Guid]", null, new string[] { "ExcludedPropery1", "ExcludedPropery2", "ExcludedProperyN", });
精彩评论