有条件地包含在html.RadioButtonFor选中属性(MVC4 /剃刀) [英] Conditionally include checked attribute in html.RadioButtonFor (MVC4/Razor)

查看:1317
本文介绍了有条件地包含在html.RadioButtonFor选中属性(MVC4 /剃刀)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你明确包括在手动codeD html元素checked属性,如单选按钮,您可以使用布尔,以确定是否该属性将在所有存在该元素的因为在这里看到。
对于那些不想点击链接,并给这个家伙的一些当之无愧交通:

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. For those not wanting to click the link and give this guy some well deserved traffic:

@ {
    布尔同意= TRUE;
}
<输入类型=复选框NAME =同意值=同意检查=@同意/>

但是,可以说,我想用 @ Html.RadioButtonFor(),同一个对象。同样的情况不会发生。

However, lets say that I want to use @Html.RadioButtonFor(), with the an object. The same does not occur.

@ Html.RadioButtonFor(M = GT; m.Property,ValueOfTextBox,新{@id =身份识别码,@class =我级,自动完成=关闭, @checked = someBoolValue})

上面给出了一个检查=真检查=假属性。

The above gives a checked="true" or checked="false" attribute.

我们的域模型,视图模型,和许多其他事物之间的差异是不让我们能够使用一些更有趣的脚手架......,可以说,如果你包括这个数量的属性,你可能会更好刚才的的使用帮助......但有一种方法,使辅助具有相同的行为与普通的HTML?

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?

我创建了一个额外的扩展方法上的的HtmlHelper 包括控制属性的presence一个布尔值,但我很想如果找出还有一个更简单/框架的行为方式来解决这个特定的问题。

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.

推荐答案

您真的不需要设置检查属性这样 - 这个助手将做它您根据属性的值。例如,如果你的模型具有财产性别并要渲染单选按钮男性和女性

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. For example if your model has property Gender and you want to render radio buttons for "Male" and "Female"

@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. Similarly

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

将呈现复选框为选中如果 IsMale = TRUE 和unchecked如果 IsMale = FALSE

will render the checkbox as checked if IsMale = true and unchecked if IsMale = false

这篇关于有条件地包含在html.RadioButtonFor选中属性(MVC4 /剃刀)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆