我试图创建一个视图,其中包含从数据库动态创建的复选框列表,然后在表单回发时检索选定列表。动态列表的复选框和模型绑定
我的EF模型包含一个类:
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; }
}
我控制器get方法:
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" />
<% } %>
我控制器POST方法:
[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
}
}
我似乎无法得到它的工作。我的基本问题是混合在代码片断意见,但回顾:
- 是我的视图模型OK? (我是否需要添加任何内容来捕获所选内容,而不仅仅是要显示的列表?)
- 究竟应该在视图中放置什么来呈现每个复选框?
- 如何在帖子后访问控制器中选定的复选框?
非常感谢你,信息的组合让我满意。下一步(当我有更多的时间)是把它绑在一个帮手,就像你有... – Jon 2010-07-13 14:24:06
有很多的资源定制助手,所以你会没事的!请享用! – 2010-07-13 15:00:05