我试图创建一个视图,其中包含从数据库动态创建的复选框列表,并在表单提交后检索所选项目的列表。
我的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
}
}
我似乎无法使它工作。我的基本问题混杂在代码片段的注释中,但是简单概括一下:
- 我的视图模型没问题吧?(我是否需要添加任何内容来捕获所选内容而不仅仅是要显示的列表?)
- 我应该在视图中放置什么来呈现每个复选框?
- 提交后如何在控制器中访问所选复选框?