动态复选框列表与模型绑定

13
我试图创建一个视图,其中包含从数据库动态创建的复选框列表,并在表单提交后检索所选项目的列表。 我的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
    }
}

我似乎无法使它工作。我的基本问题混杂在代码片段的注释中,但是简单概括一下:

  • 我的视图模型没问题吧?(我是否需要添加任何内容来捕获所选内容而不仅仅是要显示的列表?)
  • 我应该在视图中放置什么来呈现每个复选框?
  • 提交后如何在控制器中访问所选复选框?
2个回答

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>

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

<%= Html.DropDownFor(m=>m.products) %>
如果您按照 Phil Haack 的帖子操作,您的模型应该会自动绑定到控制器中。

非常感谢,这些信息的组合帮助我解决了问题。下一步(当我有更多时间时)是像你一样将其绑定到一个辅助程序中... - Jon
有很多关于自定义帮助程序的资源,所以你会没问题的!享受吧! - Dai Bok

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接