C# 复选框和模型绑定的动态列表
我试图创建一个视图,其中包含从数据库动态创建的复选框列表,然后在表单发回时检索所选复选框列表 我的EF模型包含一个类:C# 复选框和模型绑定的动态列表,c#,asp.net-mvc-2,dynamic,checkbox,model-binding,C#,Asp.net Mvc 2,Dynamic,Checkbox,Model Binding,我试图创建一个视图,其中包含从数据库动态创建的复选框列表,然后在表单发回时检索所选复选框列表 我的EF模型包含一个类: public class ItemIWouldLikeACheckboxFor { public int Id { get; set; } public string Description { get; set; } } 我有一个视图模型,其中包含以下列表: public class PageViewModel { // various other
public class ItemIWouldLikeACheckboxFor {
public int Id { get; set; }
public string Description { get; set; }
}
我有一个视图模型,其中包含以下列表:
public class PageViewModel {
// various other properties
public List<ItemIWouldLikeACheckboxFor> checkboxList { get; set; }
}
我的看法是:
<% using (Html.BeginForm()) { %>
<%-- other stuff here... %>
<% foreach (var item in checkboxList) { %>
<%: Html.CheckBox( <!-- what exactly ?????? -->) %>
<% } %>
<%-- other stuff here...%>
<input type="submit" />
<% } %>
我似乎无法让它工作。我的基本问题在代码片段中以注释的形式混合在一起,但概括一下:
- 我的视图模型可以吗?(我是否需要添加任何内容来捕获所选内容,而不是简单地显示列表?)
- 我应该在视图中放置什么来渲染每个复选框
- 发布后,如何访问控制器中选定的复选框
- 你看过吗:
我们基本上编写了自己的控件来呈现HTML格式
<label for="Products"> Select Products </label>
<ul class="checkBoxList">
<li>
<input type="hidden" value="0" name="Products.Index">
<input type="checkbox" value="3424" name="Products[0].Id" id="Products0">
<label for="Products0">iPod touch 3rd Generation</label>
</li>
<li>
<input type="hidden" value="1" name="Products.Index">
<input type="checkbox" value="3123" name="Products[1].Id" id="Products1">
<label for="Products1">Creative Zen</label>
</li>
</ul>
</div>
选择产品
-
第三代iPodtouch
-
创意禅
模型看起来不错,我们编写了一个自定义帮助程序,因此我们的aspx页面看起来像:
<%= Html.DropDownFor(m=>m.products) %>
m.products)%%>
如果您遵循phil haacks post,您的模型将自动绑定到控制器中。这也是一个很好的答案:
它有一个使用自定义编辑器模板的解决方案。非常感谢您,这些信息的组合让我感到非常满意。下一步(当我有更多的时间)是把它绑在一个像你这样的助手中…有很多关于自定义助手的资源,所以你会很好!享受吧!
<label for="Products"> Select Products </label>
<ul class="checkBoxList">
<li>
<input type="hidden" value="0" name="Products.Index">
<input type="checkbox" value="3424" name="Products[0].Id" id="Products0">
<label for="Products0">iPod touch 3rd Generation</label>
</li>
<li>
<input type="hidden" value="1" name="Products.Index">
<input type="checkbox" value="3123" name="Products[1].Id" id="Products1">
<label for="Products1">Creative Zen</label>
</li>
</ul>
</div>
<%= Html.DropDownFor(m=>m.products) %>