iNerd Blog

Model Binding To A List ASP.NET MVC

Posted in Programming by Ari on 15 July 2010

I was recently writing a code that requires Model Binding to a list. The problem was, I didn’t have a single clue on how to pass the complex object from view to controller.
Then i came across this blog post by Phil Haack, http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx, I scanned through the code and it is actually quite simple. It is all about naming the textbox or whatever it is you use to edit.

In my case, i have a Person class which contains a list of contact objects.


 public class Person
    {
        public string Age { get; set; }
        public string Company { get; set; }
        public List Contacts { get; set; }
    }

and within the Contact list i have multiple contact like Home Contact, Office Contact, Billing Contact etc. Now, to update all three contacts at once, we must follow this naming convention. The idea is to put all of them in one form and create something that resemble this.


<form action="/Home/Update" method="post">
<!-- Office -->
    <input name="[0].Address" type="text" value="Commonwealth" />
    <input name="[0].Country" type="text" value="Singapore" />
    <input name="[0].City" type="text" value="Singapore" />

    <!-- Home -->
    <input name="[1].Address" type="text" value="Pioneer" />
    <input name="[1].Country" type="text" value="Singapore" />
    <input name="[1].City" type="text" value="Singapore" />

<!-- Billing -->
    <input name="[2].Address" type="text" value="Lakeside" />
    <input name="[2].Country" type="text" value="Singapore" />
    <input name="[2].City" type="text" value="Singapore" />

    


Notice the [0] [1] and [2] follow by name. This can be easily achieved in ASP.NET MVC 2. see below



However since I’m doing it in MVC 1, heres how i did it. Messy but it works.


<table class="firstTable">
<tbody>
            <tr><td><label>address    <td><%= Html.TextArea("["+i.ToString()+"]."+"PrimaryStreet", data.PrimaryStreet)%> </td> </tr>
            <tr><td><label>country     <td><%= Html.TextBox("[" + i.ToString() + "]." + "PrimaryCountry", data.PrimaryCountry)%> </td> </tr>
            <tr><td><label>city       <td><%= Html.TextBox("[" + i.ToString() + "]." + "PrimaryTown", data.PrimaryTown)%> </td> </tr> 
</tbody>
</table>
<input type="submit" value="Save" />

That’s it for the view and heres the controller.


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Update(IList contact)
        {
                 ..........
        }

Alternatively we can do it with javascript. Read