Skip to main content

Post dictionary parameters or IEnumerable parameters to MVC controller

I found a very good artical about how to pass the dictionary or IEnumerable<T> parameters to MVC controller.

http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

So if your action requires array of objects, say Person:

public ActionResult ProcessAction(Person[] people)

Then your MVC view HTML should look like:

<input type="text" name="people[0].FirstName" value="George" />
<input type="text" name="people[0].LastName" value="Washington" />
<input type="text" name="people[1].FirstName" value="Abraham" />
<input type="text" name="people[1].LastName" value="Lincoln" />
<input type="text" name="people[3].FirstName" value="Thomas" />
<input type="text" name="people[3].LastName" value="Jefferson" />
 
If your action requires dictionary of objects, say Person with key as his Employee ID:

public ActionResult ProcessAction(IDictionary<string, Person> people)

Then your MVC view HTML should look like:
<input type="text" name="people[0].Key" value="0001" />
<input type="text" name="people[0].Value.FirstName" value="George" />
<input type="text" name="people[0].Value.LastName" value="Washington" />
<input type="text" name="people[1].Key" value="0002" />
<input type="text" name="people[1].Value.FirstName" value="Abraham" />
<input type="text" name="people[1].Value.LastName" value="Lincoln" />

Comments