简体   繁体   中英

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,

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM