如何在 ASP.NET MVC 中创建 CheckBoxListFor 扩展方法?
我知道 ASP.NET MVC Html 辅助扩展方法中有一个 ListBoxFor
扩展方法,但我一直认为复选框列表比列表框更用户友好。
旧的 WebForms 中有一个非常方便的 CheckBoxList
控件,但显然现在已经不可用了。
问题是,为什么在 ASP.NET MVC 中没有办法创建复选框列表?如何编写自己的扩展方法来创建复选框列表并以与 ListBoxFor
类似的方式运行?
I know there is a ListBoxFor
extension method among the ASP.NET MVC Html helper extension methods, but I always thought that a checkbox list is more user-friendly than a list box.
There was a very convenient CheckBoxList
control in good old WebForms, but obviously that is out of the picture now.
The question is, why is there no way in ASP.NET MVC to create a check box list? How can I write my own extension method that creates a check box list and behaves in a similar way ListBoxFor
behaves?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是 CheckBoxListFor 的强类型 HtmlHelper,它将所选项目作为视图数据模型中的数组进行处理。我选择不包装 Html.CheckBox 或 Html.CheckBoxFor 方法,因为我不希望在复选框列表中隐藏“false”字段。
请随时改进并重新发布:-)
Here is a strongly typed HtmlHelper for CheckBoxListFor that handles selected items as an array in your viewdata model. I chose not to wrapper the Html.CheckBox or Html.CheckBoxFor methods as I don't want the hidden "false" fields in my checkbox lists.
Please feel free to improve on this and repost :-)
我仍在尝试,但这似乎与默认活页夹一致,并在发布后保留用户选择。隐藏字段,真的吗? ..这会在 html5 中飞行吗?这感觉很疯狂,但我宁愿这样做,也不愿仅仅因为 ModelState.IsValid 为 false 而点击我的数据库来获取下拉列表和复选框列表。
I'm still experimenting but this seems to get along with the default binder and persists the user selections after post.. Hidden fields, really?? .. will this fly in html5 ? This feels crazy but I'd rather do this than hit my db for drop down lists and checkbox lists just because ModelState.IsValid is false..
虽然 Microsoft 员工可能是唯一能够回答为什么不存在这种辅助方法的人,但您可以尝试:
模型:
控制器:
视图:
如您所见,
EditorFor
将处理所需的所有内容。While Microsoft employees are probably the only ones that can answer why such helper method doesn't exist you could try:
Model:
Controller:
View:
As you can see
EditorFor
will handle everything that's needed.您可能对 CheckBoxList 帮助程序感兴趣Jeremiah Clark 撰写的 MVC 文章(不幸的是,该文章的日期为 2008 年 11 月,涉及 MVC 1)。
You might be interested in CheckBoxList Helper for MVC article by Jeremiah Clark (unfortunately it's dated Nov 2008 and concerns MVC 1).