如何使用 ASP.NET MVC 将字典绑定到一组复选框?
我的需要是“绑定”
Dictionary<MyType, bool>
到 asp.net mvc 中的复选框列表。
我对如何实现这一目标感到困惑。 有人可以帮助我吗?
My need is to 'bind'
Dictionary<MyType, bool>
to list of checkboxes in asp.net mvc.
I'm confused about how to accomplish that. Could anyone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设 MyType 有一个名为
Name
的字符串属性,您将从中获取复选框的名称。 请注意,我已将其更改为以MyType
作为前缀,以便我们可以在服务器上轻松区分它。 如果您有其他方法来确定哪些字段是复选框,则可能不需要此步骤。控制器(这使用 FormParameters,但您也可以尝试将带有前缀“MyType”的模型直接绑定到
Dictionary
,然后进行翻译。您也可以在客户端使用一些 javascript -side,在提交之前为每个“未选中”复选框添加
name=off
参数,这样就无需填写原始字典,因为您将能够直接导出所有的值字典元素。Assuming that MyType has a string property named
Name
from which you will get the name of the checkbox. Note that I've changed this to preface it withMyType
so we can easily distinguish it on the server. You may not need this step if you have another way to determine which fields are the checkboxes.Controller (this uses FormParameters, but you could also try model binding with prefix "MyType" directly to a
Dictionary<string,bool>
, then translate.You could also, with a bit of javascript on the client-side, add
name=off
parameters for each of the "unchecked" checkboxes before submitting and that would obviate the need to fill the original dictionary since you'll be able to directly derive the values for all of the dictionary elements.