[英]Conditional Html attribute using razor @html helpers
我正在尝试向通过 @html helper 函数生成的 html 添加一个 disable 属性,但似乎无法在 html helper 的 attrib 参数中找到一些工作。 我在下面的内容仍然会为 html 写禁用...但我无法删除它,因为然后帮助程序不起作用。
我定义了一个变量:
@{ var displayItem = (Model.TypeId == 100) }
@Html.TextBox("listitem", "", new {@class = "form-control", @disabled = (@displayItem ? "" : "disabled")})
但是因为我必须列出参数@disabled,所以会产生这样的html:
<input class="form-control" disabled="" id="listitem" name="listitem" type="text" value="" />
因为禁用被列出它禁用输入。 但是除非我给它一个参数名称,否则 html 助手不起作用。
如何在参数列表中写入禁用,以便在不应该禁用的情况下根本不显示禁用?
你可以使用
@{ 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" })
}
注意disabled控件的值是不提交的,所以一个readonly
属性可能更合适
您还可以使用字典并将其传递给 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.