[英]Conditional Html attribute using razor @html helpers
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.我正在尝试向通过 @html helper 函数生成的 html 添加一个 disable 属性,但似乎无法在 html helper 的 attrib 参数中找到一些工作。 what i have below will still write disabled for the html... but i can't remove it cause then the helper doesn't work.我在下面的内容仍然会为 html 写禁用...但我无法删除它,因为然后帮助程序不起作用。
i have a variable defined:我定义了一个变量:
@{ var displayItem = (Model.TypeId == 100) }
@Html.TextBox("listitem", "", new {@class = "form-control", @disabled = (@displayItem ? "" : "disabled")})
but because i have to list the parameter @disabled, that produces html like this:但是因为我必须列出参数@disabled,所以会产生这样的html:
<input class="form-control" disabled="" id="listitem" name="listitem" type="text" value="" />
because disabled is listed it disables the input.因为禁用被列出它禁用输入。 but the html helper doesn't work unless i give it a parameter name.但是除非我给它一个参数名称,否则 html 助手不起作用。
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?如何在参数列表中写入禁用,以便在不应该禁用的情况下根本不显示禁用?
You can use你可以使用
@{ var displayItem = (Model.TypeId == 100) }
@Html.TextBox("listitem", "", displayItem ? (object)new { @class = "form-control", disabled = "disabled" } : (object)new { @class = "form-control"});
or或
@{
var attributes = Model.TypeId == 100 ? (object)new { @class = "form-control", disabled = "disabled" } : (object)new { @class = "form-control"});
}
@Html.TextBox("listitem", "", attributes)
or a simple if
block或者一个简单的if
块
@(if Model.TypeId == 100)
{
@Html.TextBox("listitem", "", new {@class = "form-control", disabled = "disabled" })
}
else
{
@Html.TextBox("listitem", "", new {@class = "form-control" })
}
Note that the value of disabled controls are not submitted, so a readonly
attribute may be more appropriate注意disabled控件的值是不提交的,所以一个readonly
属性可能更合适
You also can use a Dictionary and pass that to the html helper:您还可以使用字典并将其传递给 html 帮助程序:
@{
var attributes = new Dictionary<string, object>
{
{ "class", "form-control" }
};
if (Model.TypeId == 100)
{
attributes.Add("disabled", "disabled");
}
}
@Html.TextBox("listitem", "", attributes)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.