我正在使用 ASP.NET MVC 构建一个应用程序,我想使用强类型 View 模型,其中包含一个名为 items 的 List
我想要显示信息的方式是作为一个表格,每行有一列人名,然后n个包含复选框的列,每个列表
我的显示工作正常,但我很难理解如何命名这些项目,以便发布的方法可以读取数据。
这是我在 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>
这段代码完美地显示了信息。但是,当我单击“提交”时,我收到“对象引用未设置”错误消息。
有人可以帮忙吗?
最佳答案
我自己解决了这个问题,这总是比得到答案更有值(value)......
这是我犯的一个愚蠢的错误:
我变了
<% 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.net-mvc - ASP.NET MVC : How to display strongly typed view model, 包含项目列表,其中也包含项目列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2559727/