aamankhaan
aamankhaan

Reputation: 491

View model property is null on POST in MVC3

I have an issue with my view where on HTTP POST the view model returns null for all of my properties.

Below is my view model.

public class CustomerVM
{
    public List<CustomerCDTO> customerCDTO { get; set; }
}

In the above view model I have created a List<CustomerCDTO> property. The CustomerCDTO class definition is as follows.

public class CustomerCDTO
{
    public string Name { get; set; }
    public bool Active { get; set; }
    public bool? IsChecked { get; set; }
}

Below is my view:

<%foreach (var item in Model.customerCDTO) {%>
<tr>
    <td style="text-align: center; width: 10%;" class="table-content-middle">
        <%if (item.Active == true)
        {%>
            <%=Html.CheckBoxFor(m=>item.Active)%>
        <%}
        else
        { %>
            <%=Html.CheckBoxFor(m=>item.Active)%>
        <%}%>
    </td>
    <td class="table-content-middle" align="center" style="width: 80%;">
        <%: item.Name%>
    </td>
</tr>
<%} %> 

When I perform an HTTP GET everything works as expected but on POST I am getting null for CustomerVM.customerCDTO.

Please suggest what should I do to make it work.

thanks,

Upvotes: 1

Views: 2978

Answers (1)

Jon
Jon

Reputation: 437366

That's because you are not getting to each CustomerCDTO with expressions containing the information that it's part of a List.

Use a for loop instead:

<%for (var i = 0; i < Model.customerCDTO.Count; ++i)

And refer to the elements with expressions like

<%=Html.CheckBoxFor(m => m.customerCDTO[i].Active)%>

Basically you need to have the expression m => ... resolve to the property you are interested in starting from m, not from some other variable.

Upvotes: 4

Related Questions