将 KeyValuePair 列表绑定到复选框
我正在使用 ASP.Net MVC 和 C#。我有一个模型,其中有一个用于过滤条件的成员。该成员是一个IList>。键包含要显示的值,该值表明是否选择了该过滤器。我想将其绑定到我视图上的一堆复选框。我就是这样做的。
<% for(int i=0;i<Model.customers.filterCriteria.Count;i++) { %>
<%=Html.CheckBoxFor(Model.customers.filterCriteria[i].value)%>
<%=Model.customers.filterCriteria[i].key%>
<% } %>
这将正确显示所有复选框。但是,当我在控制器中提交表单时,无论我在视图中选择什么,过滤条件都会为空。
从 这篇 帖子中,我得到了创建单独属性的提示。但这对于 IList 来说如何运作呢?请问有什么建议吗?
I am using ASP.Net MVC with C#. I have a model which has a member for filter criteria. This member is a IList>. The key contains value to display and the value tells if this filter is selected or not. I want to bind this to bunch of checkboxes on my view. This is how I did it.
<% for(int i=0;i<Model.customers.filterCriteria.Count;i++) { %>
<%=Html.CheckBoxFor(Model.customers.filterCriteria[i].value)%>
<%=Model.customers.filterCriteria[i].key%>
<% } %>
This displays all checkboxes properly. But when I submit my form, in controller, I get null for filtercriteria no matter what I select on view.
From this post I got a hint for creating separate property. But how will this work for IList..? Any suggestions please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
KeyValuePair
结构的问题在于它具有私有设置器,这意味着默认模型绑定器无法在 POST 操作中设置它们的值。它有一个特殊的构造函数,需要使用它来传递键和值,但当然默认模型绑定程序不知道该构造函数,并且它使用默认的构造函数,因此除非您为这种类型编写自定义模型绑定程序,否则您将无法使用该构造函数。将无法使用它。我建议您使用自定义类型而不是
KeyValuePair
。因此,一如既往,我们从视图模型开始:
然后是控制器:
以及相应的
~/Views/Home/Index.aspx
视图:最后我们为
中的 Item 类型编写自定义的编辑器模板>~/Views/Shared/EditorTemplates/Item.ascx
或~/Views/Home/EditorTemplates/Item.ascx
(如果此模板仅特定于 Home 控制器且不重复使用) :我们已经实现了两件事:清理丑陋的
for
循环中的视图,并使模型绑定器成功绑定 POST 操作中的复选框值。The problem with the
KeyValuePair<TKey, TValue>
structure is that it has private setters meaning that the default model binder cannot set their values in the POST action. It has a special constructor that need to be used allowing to pass the key and the value but of course the default model binder has no knowledge of this constructor and it uses the default one, so unless you write a custom model binder for this type you won't be able to use it.I would recommend you using a custom type instead of
KeyValuePair<TKey, TValue>
.So as always we start with a view model:
then a controller:
and the corresponding
~/Views/Home/Index.aspx
view:and finally we write a customized editor template for the Item type in
~/Views/Shared/EditorTemplates/Item.ascx
or~/Views/Home/EditorTemplates/Item.ascx
(if this template is only specific to the Home controller and not reused):We have achieved two things: cleaned up the views from ugly
for
loops and made the model binder successfully bind the checkbox values in the POST action.