ASP.NET MVC: Binding arrays in model

One of the great features of ASP.NET MVC is the automatic model binding. This is one of those things which look trivial but in fact are very very important. This reduces the LoC and complexity by miles. For instance, you want to present a number of text inputs to the user and read multiple locations:

 

<input type="text" name="Location1" id="Location1" />
<input type="text" name="Location2" id="Location2" />
<input type="text" name="Location3" id="Location3" />

 

Now this would be tedious in your action:

 

public ActionResult UserData(string location1, string location2, string2)
{
   // do somthing
   return View();
}

 

And what if you don’t know how many locations would there be? That is where MVC shows the magic. Bring it on:

public ActionResult UserData(string[] locations)
{
   // do somthing
   return View();
}

 

 

Hmmm… pretty simple. Now keep adding location inputs in your view and MVC will bind all that to the location parameter. The key here is that the name of your input controls should be location as well with an index like a proper array.

 

<input type="text" name="location[0]" id="location[0]" />
<input type="text" name="location[1]" id="location[1]" />
<input type="text" name="location[2]" id="location[2]" />

 

The magic of model binding does not end here. That is, if you have another array of postcodes along with locations the method signature of your action will look dirty again. The solution for this in MVC is to bind everything in the model object and pass that object over to the action. Now your model object will look like this:

 

public class HomeModel
{
     public IList<string> Locations { get; set; }
     public IList<string> PostCodes { get; set; }
}

 

 

And the action signature will accept only one parameter which is the model.

 

public ActionResult UserData(HomeModel model)

 

Yes, everything is in that object, pretty neat. Make sure your view inherits from System.Web.Mvc.ViewPage<HomeModel> so it knows about its model type.

 

 

 

Share this post :

Advertisements

One thought on “ASP.NET MVC: Binding arrays in model

  1. Hi,

    I tried this in asp.net mvc 3 and you need to have the same input names :
    location => locationS.
    Thank you for this post tho :-).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s