Model Binding to a list in ASP.NET MVC came in very handy today so I thought I would just show a quick example of model binding to a list of simple types ( e.g. strings ). Note that you can bind to a list of complex types, too, but that can be the subject of another post as I didn't need that functionality today :)
Quite simply, I needed to bind to a list of strings in a View. Didn't really care anything more about those strings other than I just needed a simple way for a user to input a list of strings and then capture those strings for processing.
ASP.NET MVC makes this very simple. In the view, one can add any number of textboxes and give them all the same name. Here is a list of 5 textboxes with the same name - Name.
<% Html.BeginForm(); %>
<%= Html.TextBox("Name") %>
<%= Html.TextBox("Name") %>
<%= Html.TextBox("Name") %>
<%= Html.TextBox("Name") %>
<%= Html.TextBox("Name") %>
<input type="submit" value="Save" />
<% Html.EndForm(); %>
Now in the ASP.NET MVC Controller Action you can just bind to an IList<string> with the argument being the same name as the name of the textboxes - Name.
[HttpPost]
public ActionResult Index(IList<string> name)
{
// Do Something...
}
When posted back to the controller all the names will be added to the list for one to process on the server. That is very cool.

Comments