开发者

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

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

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<Item>, and checked based on whether the Person's List<int> (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 开发者_C百科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?


I've solved this myself, which is always more rewarding than being given the answer...

It was a stupid mistake I was making:

I changed

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

To

<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>

<% for( int p = 0; a<Model.people.Count; p++){ %>

<% var person = Model.people[p]; %>

Then used that when creating the checkboxes:

<% if( person.items.Contains(i.id) ) { %>

<%= Html.CheckBox( "vm.people[" + p + "].items[" + i.id + "]", true ) %>

<% } else { %>

<%= Html.CheckBox( "vm.people[" + p + "].items[" + i.id + "]", false ) %>

<% } %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜