与HTML辅助条件HTML属性 [英] Conditional html attribute with Html Helper
问题描述
我使用的HTML帮助来创建一个复选框。待一定条件下,我想在禁用
属性添加到htmlAttribute对象。我有以下的code:
@if(Model.IsAuthorized)
{
@ Html.CheckBoxFor(X => @ Model.Property,新{@class =输入级})
}
其他
{
@ Html.CheckBoxFor(X => @ Model.Property,新{@class =输入级,@disabled =已禁用})
}
我想使这个code更简洁。有没有一种方法,以有条件地在一条线/添加某些HTML属性没有一个块中的条件?
虽然你可以使用
<?pre> @ Html.CheckBoxFor(M = GT; m.Property,Model.IsAuthorized(对象)新的{@class =输入级,禁用=禁用}: (对象)新的{@class =输入级});
为此在code的一条线,你的情况可能会导致模型绑定失败。
的 CheckBoxFor()
方法生成2路输入,以值=真
和隐藏输入一个复选框与值=FALSE
。在属性
的初始值的情况下真正
和 IsAuthorized
是真正
的结果是,该复选框被禁用,将不会发布一个值。然而,隐藏的输入将被提交并绑定到你的模型,从而属性
是假
(当它应该是真正
)
为了处理模型绑定正确的话,您将需要如果
块
@if(Model.IsAuthorized)
{
@ Html.CheckBoxFor(X =&GT; m.Property,新{@class =输入级})
}
其他
{
@ Html.HiddenFor(M = GT; m.Property)//需要回发的初始值
&LT;输入类型=复选框@(?Model.Property选中日期null)禁用/&GT;
}
I am using a Html helper to create a checkbox. Pending some condition, I want to add the disabled
attribute to the htmlAttribute object. I have the following code:
@if (Model.IsAuthorized)
{
@Html.CheckBoxFor(x => @Model.Property, new { @class = "input-class" })
}
else
{
@Html.CheckBoxFor(x => @Model.Property, new { @class = "input-class", @disabled = "disabled" })
}
I'd like to make this code more terse. Is there a way to conditionally add certain html attributes in one line/without a block conditional?
While you could use
@Html.CheckBoxFor(m => m.Property, Model.IsAuthorized ? (object)new { @class = "input-class", disabled = "disabled" } : (object)new { @class = "input-class"});
to do this in one line of code, in your case it may result in model binding failing.
The CheckBoxFor()
method generates 2 inputs, a checkbox with value="True"
and a hidden input with value="False"
. In the case where the initial value of Property
is true
and IsAuthorized
is true
the result is that the checkbox is disabled and will not post a value. However the hidden input will be submitted and bind to your model, resulting in Property
being false
(when it should be true
)
In order to handle model binding correctly, you will need the if
block
@if (Model.IsAuthorized)
{
@Html.CheckBoxFor(x => m.Property, new { @class = "input-class" })
}
else
{
@Html.HiddenFor(m => m.Property) // necessary to post back the initial value
<input type="checkbox" @(Model.Property ? "checked" : null) disabled />
}
这篇关于与HTML辅助条件HTML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!