2010-07-13 80 views
12

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

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

我似乎无法得到它的工作。我的基本问题是混合在代码片断意见,但回顾:

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

回答

14

你见过: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) %> 

如果按照菲尔骇客发帖,你的模型应该自动绑定在你的控制器中。

+0

非常感谢你,信息的组合让我满意。下一步(当我有更多的时间)是把它绑在一个帮手,就像你有... – Jon 2010-07-13 14:24:06

+0

有很多的资源定制助手,所以你会没事的!请享用! – 2010-07-13 15:00:05