【问题标题】:Dynamic list of checkboxes and model binding复选框和模型绑定的动态列表
【发布时间】:2011-03-15 04:19:30
【问题描述】:

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

我的 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; }
}

我的控制器获取方法:

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
    }
}

我似乎无法让它工作。我的基本问题与代码 sn-ps 中的 cmets 混合在一起,但回顾一下:

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

【问题讨论】:

    标签: c# asp.net-mvc-2 dynamic checkbox model-binding


    【解决方案1】:

    你看到了吗: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 haacks 的帖子,您的模型应该会自动绑定到您的控制器中。

    【讨论】:

    • 非常感谢,这些信息让我成功了。下一步(当我有更多时间时)是像你一样把它绑在一个助手中......
    • 有很多关于自定义助手的资源,所以你会没事的!享受吧!
    【解决方案2】:

    这个问题的答案也很好:CheckBoxList multiple selections: difficulty in model bind back

    它有一个使用自定义编辑器模板的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 2018-07-26
      相关资源
      最近更新 更多