简体   繁体   English

有条件地在html.RadioButtonFor(MVC4 / Razor)中包含checked属性

[英]Conditionally include checked attribute in html.RadioButtonFor (MVC4/Razor)

When you explicitly include the checked attribute in a manually coded html element such as a radio button, you can use a bool to determine if that attribute will exist at all on that element as seen here. 当您在手动编码的html元素(例如单选按钮)中明确包含checked属性时,可以使用bool来确定该元素是否在该元素上完全存在,如此处所示。 For those not wanting to click the link and give this guy some well deserved traffic: 对于那些不想点击链接并给这个人一些当之无愧的流量的人:

@{ bool agree = true; } <input type="checkbox" name="agree" value="agree" checked="@agree" />

However, lets say that I want to use @Html.RadioButtonFor() , with the an object. 但是,假设我想使用@Html.RadioButtonFor()和一个对象。 The same does not occur. 同样的情况也不会发生。

@Html.RadioButtonFor(m => m.Property, "ValueOfTextBox", new { @id = "MyId", @class = "my-class", autocomplete = "off", @checked = someBoolValue }) . @Html.RadioButtonFor(m => m.Property, "ValueOfTextBox", new { @id = "MyId", @class = "my-class", autocomplete = "off", @checked = someBoolValue })

The above gives a checked="true" or checked="false" attribute. 上面给出了checked="true"checked="false"属性。

Discrepancies between our Domain Model, View Model, and many other things are keeping us from being able to use some more interesting scaffolding... and arguably if you're including this number of attributes you may be better off just not using the helper... but is there a way to make the helper have the same behavior as the plain html? 我们的域模型,视图模型和许多其他事物之间的差异使我们无法使用一些更有趣的脚手架......并且可以说,如果你包含这些属性,你可能最好不要使用帮助器。 ..但有没有办法让助手具有与普通html相同的行为?

I've created an additional extension method on HtmlHelper to include a bool value that controls the presence of the attribute, but I would love to find out if there is a more straightforward/framework behavior way to solve this particular issue. 我在HtmlHelper上创建了一个额外的扩展方法,以包含一个控制属性存在的bool值,但是我想知道是否有更简单的/框架行为方式来解决这个特定的问题。

You really don't need to set the checked attribute this way - the helper will do it for you based on the value of the property. 您真的不需要以这种方式设置checked属性 - 帮助程序将根据属性的值为您执行此操作。 For example if your model has property Gender and you want to render radio buttons for "Male" and "Female" 例如,如果您的模型具有属性Gender并且您想要为“男性”和“女性”呈现单选按钮

@Html.RadioButtonFor(m => m.Gender, "Male")<span>Male</span>
@Html.RadioButtonFor(m => m.Gender, "Female")<span>Female</span>

and the value of Gender is "Female", then when the page is rendered the second radio button will be checked. Gender值为“Female”,然后在呈现页面时,将检查第二个单选按钮。 Similarly 同样

@Html.CheckboxFor(m => m.IsMale)

will render the checkbox as checked if IsMale = true and unchecked if IsMale = false 将呈现复选框为选中如果IsMale = true和未选中如果IsMale = false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM