views:

52

answers:

1

Hi everyone,

I have the following complex model: Category - has -> List which has -> List

I am trying to make a create action where I can pull all the existing categories and insert for each category one List all together, including the sub items. For example: -Cat1 -- NewItemGroup1 --- NewItem1 --- NewItem2 --- NewItem3 --- NewItem4

-Cat2 -- NewItemGroup2 --- NewItem1 --- NewItem2 --- NewItem3 --- NewItem4

My questions, can I achieve this using the default modelbinder? or should I use something else? and how much work would that add :) ?

Thanks!

+3  A: 

You can do complex objects and lists with the default modelbinder, you just have to index your posted data so that it can properly figure it out.

Phil Haack's article Model Binding to a List covers what you need to do. In a nutshell, just index your list fields with a hidden field like so:

<input type="hidden" name="products.Index" value="0" />
<input type="text" name="products[0].Name" value="Beer" />
<input type="text" name="products[0].Price" value="7.32" />

The named products.Index field describes that there is an index "0" for your "products" list. The Name and Price fields are then properties of the object at index 0. Note that the index doesn't have to be an integer, so if you're binding to a dictionary, you can use anything as your index value.

womp
I have seen this soluction before.. but in my case, it's a list inside another list. So, am wondering if I really can rely on default modelbinders?
OneDeveloper
Yes, you can. You can nest your property names however deep you want. It could be Category1[0].NewItemGroup1[0], etc. etc.
womp
this is really helpful. thnx!
OneDeveloper