【问题标题】:ASP.NET MVC: How to display strongly typed view model, containing list of items, which also contain list of items?ASP.NET MVC:如何显示强类型视图模型,包含项目列表,其中还包含项目列表?
【发布时间】:2011-02-03 07:43:36
【问题描述】:

我正在使用 ASP.NET MVC 构建一个应用程序,我想使用强类型视图模型,其中包含一个名为 items 的 List ,其中包含一个 id int 和 itemName 字符串。视图模型还包含一个名为 people 的 List,而 Person 类包含一个 List

我想要显示信息的方式是作为一个表格,每一行都有一个人名列,然后是 n 个包含复选框的列,每个 List 一个,并根据是否检查Person 的 List(称为 items)包含 Item 的 id。

我的显示器工作正常,但我很难理解如何命名项目,以便发布的方法可以读取数据。

这是我在 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>

这段代码完美地显示了信息。但是,当我单击提交时,我收到未设置对象引用.. 错误消息。

有人可以帮忙吗?

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    我自己解决了这个问题,这总是比得到答案更有价值......

    这是我犯的一个愚蠢的错误:

    我变了

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

    <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]; %>
    

    然后在创建复选框时使用它:

    <% 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 ) %>
    
    <% } %>
    

    【讨论】:

    • 您可以编辑您的答案并将您的 asp 代码放入“代码”块中; ) 奖励:在 MVCContrib 项目中有一组 MVC 助手,可让您使用 lambdas 而不是魔术字符串。希望对你有帮助
    猜你喜欢
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2023-03-14
    相关资源
    最近更新 更多