MVC 将布尔值绑定/发布到单选按钮
我的模型中有一个列具有 NULLABLE 布尔值。现在在我的视图(用于编辑)上,我想将其绑定到两个单选按钮:是和;否。如果该值为 null,则只需取消选中这两个单选按钮即可。我该怎么做呢?
谢谢。
I have a column in my Model with a NULLABLE boolean value. Now on my View (for editing), I would like to bind that to two radiobuttons: Yes & No. If the value is null, then just have the two radiobutton un-checked. How would I go to do that?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一旦您选择了单选按钮,就无法取消选择它(作为用户)。我建议,如果您确实需要一个三值结果,那么您可以使用三个单选按钮 - 是、否、不关心。
Once you have selected a radio button, there's really no way to unselect it (as a user). I'd suggest that if you really need a three-valued result, that you have three radio buttons -- Yes, No, Don't care.
我可以稍后阅读这篇文章,但是这是我的解决方案,它也可以处理设置值。这使用了编辑器模板。您将需要指定编辑器模板名称。我将我的命名为“NullableBool”
I can across this post late, however here is my solution which handles the setting the values as well. This used an Editor template. You will need to specify the Editor template name. I called mine 'NullableBool'
使用多个 Html.RadioButtonFor (m => m.Foo, "true") 似乎会生成无效的 HTML,因为它生成具有相同 ID 的控件:
我已经通过直接在 html 中制作单选按钮解决了这个问题:
请确保根据使用的视图模型命名单选按钮,例如: Model.Filter.HasImage 被命名为: Filter.HasImage 以与模型绑定一起使用
“html helper”如下所示:
The use of multiple Html.RadioButtonFor (m => m.Foo, "true") seems to generate invalid HTML, because it generates controls with identical IDs:
I have solved this by making the radio buttons directly in html:
make sure to name the radio buttons according to the used viewmodel, eg: Model.Filter.HasImage is named: Filter.HasImage to work with model binding
The "html helper" looks like this:
这是解决问题的捷径。这是一个非常古老的 ASP 问题。
问题是您需要设置
checked
属性,因为Html.RadioButtonFor
不会检查基于可为空布尔值的单选按钮(这似乎是一个缺陷)。另外,通过将单选按钮放在标签标记内,您可以通过单击标签来选择值。
共享/EditorTemplates/Boolean.cshtml
This is a razor solution to the problem. This is a very old ASP question.
The problem is that you need to set the
checked
attribute because theHtml.RadioButtonFor
does not check a radio button based on a nullable bool (which appears to be a flaw).Also by putting the radio buttons inside of the label tag, you can select value by clicking the label.
Shared/EditorTemplates/Boolean.cshtml