ASP.NET MVC: How to display strongly typed view model, containing list of items, which also contain

Posted by Sam Delaney on Stack Overflow See other posts from Stack Overflow or by Sam Delaney
Published on 2010-04-01T10:36:18Z Indexed on 2010/04/01 11:23 UTC
Read the original article Hit count: 325

Filed under:

Hi, I'm building an app using ASP.NET MVC which I want to use a strongly type view model, which contains a List called items which contains an id int and itemName string. The view model also conatins a List called people, and the Person class contains a List.

The way I want to display the information is as a table, with each row having a column of Person name, then n number of columns which contain checkboxes, one for each of the List, and checked based on whether the Person's List (called items) contains the id of the Item.

I have the display working fine, but I'm struggling to understand how to name the items so that the posted method can read the data.

This is what I have in the BeginForm:

        <table cellpadding="20">
            <thead>
                <th>Person name</th>

                      <!-- for each of the items, create a column with the item name -->
                <% foreach( var i in Model.items ) { %>
                <th><%= Html.Encode(i.itemName) %></th>
                <% } %>

            </thead>

        <% foreach( var p in Model.people ) { %>

            <tr>
                <td><%= Html.Encode(p.name) %></td>

         <!-- for each item, create a column with a checkbox -->
                <% foreach( var i in Model.items ) { %>
                <td>
                <% if( p.items.Contains(i.id) ) { %>
                   <!-- vm is the name of the view model passed to the view -->
                    <%= Html.CheckBox( "vm.people[" + p.id + "].items[" + i.id + "]", true ) %>
                <% } else { %>
                    <%= Html.CheckBox( "vm.people[" + p.id + "].items[" + i.id + "]", false ) %>
                <% } %>
                </td>
                <% } %>
            </tr>

        <% } %>
        </table>

And this code displays the information perfectly. When I click submit, however, I get an Object Reference Not Set.. error message.

Can anyone help with this please?

© Stack Overflow or respective owner

Related posts about asp.net-mvc