.net – Passing Controller a FormCollection and an IList

.netasp.net-mvcasp.net-mvc-2

I have a form which contains a whole heap of data entry fields that will be completed by the user including some elements where the user can dictate how many of the same items they will enter. This is as is being used in Phil Haack's blog entry Model Binding To A List.

I am successfully using JQuery to create the extra form elements, correctly indexed, etc. My issue is the best way to actually read these within my Controller. The Controller in the article only expects one object, IList<Product> whereas my Controller already expects a FormCollection form and now I am trying to also send it an IList<Itmes> as well.

Should I be adding this to the parameters expected by the Controller or accessing via form["items"] or something else?

View

<form action="/MyItems/Add" method="post">
   <input type="text" name="Title" value="" />

   <input type="hidden" name="myItem.Index" value="0" />
   <input id="item[0].Amount" name="item[0].Amount" type="text" value="" />
   <input id="item[0].Name" name="item[0].Name" type="text" value="" />

   <input type="hidden" name="myItem.Index" value="1" />
   <input id="item[1].Amount" name="item[1].Amount" type="text" value="" />
   <input id="item[1].Name" name="item[1].Name" type="text" value="" />
</form>

Controller

public ActionResult Add(FormCollection form)
{
    string Title = form["Title"];
    List<Item> Items = form["items"].ToList();
}

DTO

public class Item()
{
    int Amount {get; set; };
    string Name {get; set; };
}

Best Solution

You could just add the myItem as a parameter like so:

public ActionResult Add(FormCollection form, List<Item> myItem)
{
}

It will then bind automatically from the form data and populate the myItem parameter.