带有 Html Helper 的条件 html 属性 [英] Conditional html attribute with Html Helper
问题描述
我正在使用 Html 助手来创建复选框.在某些条件下,我想将 disabled
属性添加到 htmlAttribute 对象.我有以下代码:
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" })
}
我想让这段代码更简洁.有没有办法在一行/没有条件块的情况下有条件地添加某些 html 属性?
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?
推荐答案
虽然你可以使用
@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.
CheckBoxFor()
方法生成 2 个输入,一个带有 value="True"
的复选框和一个带有 value="False"
的隐藏输入>.在 Property
的初始值为 true
且 IsAuthorized
为 true
的情况下,结果是复选框是禁用并且不会发布值.然而,隐藏的输入将被提交并绑定到您的模型,导致 Property
为 false
(当它应该是 true
)
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
)
为了正确处理模型绑定,您将需要 if
块
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 Helper 的条件 html 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!