将KeyValuePair列表绑定到复选框

| 我正在将ASP.Net MVC与C#一起使用。我有一个模型,其中包含过滤条件的成员。该成员是IList>。键包含要显示的值,该值指示是否选择了此过滤器。我想将此绑定到我视图上的一堆复选框。这就是我的方法。
<% for(int i=0;i<Model.customers.filterCriteria.Count;i++) { %>
<%=Html.CheckBoxFor(Model.customers.filterCriteria[i].value)%>&nbsp;
<%=Model.customers.filterCriteria[i].key%>
<% } %>
这将正确显示所有复选框。但是,当我提交表单时,在控制器中,无论我在视图上选择什么,都会为filtercriteria获取null。 从这篇文章中,我得到了创建单独属性的提示。但是,这对于IList ..将如何工作?有什么建议吗?     
已邀请:
“ 1”结构的问题在于它具有私有设置程序,这意味着默认模型绑定程序无法在POST操作中设置其值。它有一个特殊的构造函数,需要使用它来传递键和值,但是默认模型绑定程序当然不了解此构造函数,并且使用默认的构造函数,因此除非您为此类型编写自定义模型绑定程序,否则将无法使用它。 我建议您使用自定义类型而不是
KeyValuePair<TKey, TValue>
。 因此,与往常一样,我们从视图模型开始:
public class Item
{
    public string Name { get; set; }
    public bool Value { get; set; }
}

public class MyViewModel
{
    public IList<Item> FilterCriteria { get; set; }
}
然后是一个控制器:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            FilterCriteria = new[] 
            {
                new Item { Name = \"Criteria 1\", Value = true },
                new Item { Name = \"Criteria 2\", Value = false },
                new Item { Name = \"Criteria 3\", Value = true },
            }
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // The model will be correctly bound here
        return View(model);
    }
}
和相应的“ 5”视图:
<% using (Html.BeginForm()) { %>
    <%= Html.EditorFor(x => x.FilterCriteria) %>
    <input type=\"submit\" value=\"OK\" />
<% } %>
最后,我们在
~/Views/Shared/EditorTemplates/Item.ascx
~/Views/Home/EditorTemplates/Item.ascx
中为Item类型编写一个定制的编辑器模板(如果该模板仅特定于Home控制器且未重用):
<%@ Control 
    Language=\"C#\" 
    Inherits=\"System.Web.Mvc.ViewUserControl<AppName.Models.Item>\" 
%>
<%= Html.CheckBoxFor(x => x.Value) %>
<%= Html.HiddenFor(x => x.Name) %>
<%= Html.Encode(Model.Name) %>
我们已经完成了两件事:清理丑陋的
for
循环中的视图,并使模型绑定器成功绑定POST操作中的复选框值。     

要回复问题请先登录注册