使用razor @html帮助器的条件HTML属性 [英] Conditional Html attribute using razor @html helpers
问题描述
我正在尝试将禁用属性添加到通过@html帮助器函数生成的html,但似乎无法在html帮助器的attrib参数中起作用.我下面的内容仍然会针对html禁用...但是我无法删除它,原因是帮助器无法正常工作.
I'm trying to add a disable attribute to the html that is generated via @html helper functions but can't seem to get something working that works in the attrib parameters of the html helper. what i have below will still write disabled for the html... but i can't remove it cause then the helper doesn't work.
我定义了一个变量:
@{ var displayItem = (Model.TypeId == 100) }
@Html.TextBox("listitem", "", new {@class = "form-control", @disabled = (@displayItem ? "" : "disabled")})
但是因为我必须列出参数@disabled,所以生成的HTML如下所示:
but because i have to list the parameter @disabled, that produces html like this:
<input class="form-control" disabled="" id="listitem" name="listitem" type="text" value="" />
因为列出了禁用,它会禁用输入.但是,除非我给它提供一个参数名称,否则html helper不会起作用.
because disabled is listed it disables the input. but the html helper doesn't work unless i give it a parameter name.
如何在参数列表中写入禁用的内容,以便在不应该禁用的情况下完全不显示禁用的内容?
How to write the disabled in the parameter list so that disabled doesn't show at all if it's not supposed to be disabled?
推荐答案
您可以使用
@{ var displayItem = (Model.TypeId == 100) }
@Html.TextBox("listitem", "", displayItem ? (object)new { @class = "form-control", disabled = "disabled" } : (object)new { @class = "form-control"});
或
@{
var attributes = Model.TypeId == 100 ? (object)new { @class = "form-control", disabled = "disabled" } : (object)new { @class = "form-control"});
}
@Html.TextBox("listitem", "", attributes)
或简单的if
块
@(if Model.TypeId == 100)
{
@Html.TextBox("listitem", "", new {@class = "form-control", disabled = "disabled" })
}
else
{
@Html.TextBox("listitem", "", new {@class = "form-control" })
}
请注意,未提交禁用控件的值,因此readonly
属性可能更合适
Note that the value of disabled controls are not submitted, so a readonly
attribute may be more appropriate
这篇关于使用razor @html帮助器的条件HTML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!