复选框和模型绑定的动态列表 [英] Dynamic list of checkboxes and model binding
问题描述
我试图创建一个视图,其中包含从数据库动态创建的复选框列表,然后在发回表单时检索所选复选框的列表。
I'm trying to create a view that contains a list of checkboxes that is dynamically created from a database, and then retrieve the list of selected ones when the form is posted back.
我的EF模型包含一个类:
My EF model contains a class:
public class ItemIWouldLikeACheckboxFor {
public int Id { get; set; }
public string Description { get; set; }
}
我有一个视图模型包含这些列表:
I have a view model that contains a list of these:
public class PageViewModel {
// various other properties
public List<ItemIWouldLikeACheckboxFor> checkboxList { get; set; }
}
我的控制器get方法:
My controller get method:
public ActionResult Create() {
var viewModel = new PageViewModel();
viewModel.checkboxList = db.ItemIWouldLikeACheckboxFors.ToList();
return View(viewModel);
}
我的观点:
<% using (Html.BeginForm()) { %>
<%-- other stuff here... %>
<% foreach (var item in checkboxList) { %>
<%: Html.CheckBox( <!-- what exactly ?????? -->) %>
<% } %>
<%-- other stuff here...%>
<input type="submit" />
<% } %>
我的控制器发布方法:
[HttpPost]
public ActionResult Create(PageViewModel viewModel) {
// do stuff with other fields
// I would like to do something like:
foreach (var item in selectedCheckBoxes) {
// do stuff
}
}
我似乎无法使用它。我的基本问题在代码片段中作为注释混合在一起,但重述如下:
I can't seem to get it to work. My basic questions are mixed in as comments in the code snippets, but to recap:
- 我的视图模型是否可以? (我需要添加任何东西来捕获选择的列表,而不是简单的列表显示?)
- 我应该在视图中呈现每个复选框究竟应该是什么? >
- 如何在帖子后访问控制器中的所选复选框?
推荐答案
我们基本上写了我们的自己控制渲染HTML像
We basically wrote our own control to render the HTML like
<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>
Model Looks好的,我们写了一个自定义助手,所以我们的aspx页面看起来像:
Model Looks Ok, we wrote a custom helper, so our aspx pages look like:
<%= Html.DropDownFor(m=>m.products) %>
如果你跟随phil haacks发布,你的模型应该自动绑定在你的控制器。
If you follow phil haacks post, your model should automatically bind in your controller.
这篇关于复选框和模型绑定的动态列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!