MVC Model Binding Complex Collections Gotcha

09.15.10

Problem:

Despite using proper MVC binding HTML conventions values are not being bound correctly to your list. The list may have the correct number of objects but all the value are set to default.

Solution:

Use properties instead of public variables.

Correct Html Markup.

<div>Id</div>
<div>
    <input id="Products_0__Id"
           name="Products[0].Id"
           type="text"
           value="1" />
</div>
<div>Name</div>
<div>
    <input id="Products_0__Name"
           name="Products[0].Name"
           type="text"
           value="Product 1" />
</div>
<div>Quantity</div>
<div>
    <input id="Products_0__Quantity"
           name="Products[0].Quantity"
           type="text"
           value="2" />
</div>
<div>Unit Price</div>
<div>
    <input id="Products_0__UnitPrice"
           name="Products[0].UnitPrice"
           type="text"
           value="200.00" />
</div>

Incorrect View Model:

public class Basket
{
    public List<Product> Products { get; set; }
    public Totals Totals { get; set;}
}
public class Product
{
    public int Id;
    public string Name;
    public int Quantity;
    public decimal UnitPrice;
}

Correct View Model:

public class Basket
{
    public List<Product> Products { get; set; }
    public Totals Totals { get; set;}
}
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
}