复选框和模型绑定的动态列表

Jon*_*Jon 12 c# checkbox dynamic model-binding asp.net-mvc-2

我正在尝试创建一个视图,其中包含从数据库动态创建的复选框列表,然后在回发表单时检索所选复选框的列表.

我的EF模型包含一个类:

public class ItemIWouldLikeACheckboxFor {
    public int Id { get; set; }
    public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有一个包含以下列表的视图模型:

public class PageViewModel {
    // various other properties
    public List<ItemIWouldLikeACheckboxFor> checkboxList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的控制器获取方法:

public ActionResult Create() {
    var viewModel = new PageViewModel();
    viewModel.checkboxList = db.ItemIWouldLikeACheckboxFors.ToList();
    return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)

我的看法:

<% using (Html.BeginForm()) { %>
    <%-- other stuff here... %>

    <% foreach (var item in checkboxList) { %>
        <%: Html.CheckBox( <!-- what exactly ?????? -->) %>
    <% } %>

    <%-- other stuff here...%>
    <input type="submit" />
<% } %>
Run Code Online (Sandbox Code Playgroud)

我的控制器发布方法:

[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
    }
}
Run Code Online (Sandbox Code Playgroud)

我似乎无法让它发挥作用.我的基本问题在代码片段中作为注释混合在一起,但回顾一下:

  • 我的视图模型好吗?(我是否需要添加任何内容来捕获选定的内容,而不是仅显示要显示的列表?)
  • 我应该在视图中放置什么来呈现每个复选框?
  • 发布后如何访问控制器中的所选复选框?

Dai*_*Bok 15

你见过:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

我们基本上编写了自己的控件来呈现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>
Run Code Online (Sandbox Code Playgroud)

模型看起来不错,我们写了一个自定义帮助器,所以我们的aspx页面看起来像:

<%= Html.DropDownFor(m=>m.products) %>
Run Code Online (Sandbox Code Playgroud)

如果您关注phil haacks post,您的模型应该会自动绑定到您的控制器中.