复选框和模型绑定的动态列表 [英] Dynamic list of checkboxes and model binding

查看:144
本文介绍了复选框和模型绑定的动态列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,当窗体回创建包含动态从数据库中创建一个复选框列表视图,然后检索选定的名单。

I'm trying to create a view that contains a list of checkboxes that is dynamically created from a database, and then retrieve the list of selected ones when the form is posted back.

我的EF模型包含一个类:

My EF model contains a class:

public class ItemIWouldLikeACheckboxFor {
    public int Id { get; set; }
    public string Description { get; set; }
}

我有一个包含这些列表的视图模型:

I have a view model that contains a list of these:

public class PageViewModel {
    // various other properties
    public List<ItemIWouldLikeACheckboxFor> checkboxList { get; set; }
}

我的控制器get方法:

My controller get method:

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方法:

My controller post method:

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

我似乎无法得到它的工作。我的基本问题是混合作为code段的意见,但回顾一下:

I can't seem to get it to work. My basic questions are mixed in as comments in the code snippets, but to recap:


  • 是我的看法模式好不好? (我需要添加任何捕捉选择的,而不是简单地在列表中显示?)

  • 正是我应该把什么视图来呈现每个复选框?

  • 如何访问控制器中的选定复选框后门柱?

推荐答案

你见过:<一href=\"http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx\">http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx?

我们基本上是写我们自己的控制,以使像

We basically wrote our own control to render the HTML like

<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页面如下:

Model Looks Ok, we wrote a custom helper, so our aspx pages look like:

<%= Html.DropDownFor(m=>m.products) %>

如果您按照菲尔haacks后,你的模型应该自动绑定在你的控制器。

If you follow phil haacks post, your model should automatically bind in your controller.

这篇关于复选框和模型绑定的动态列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆