我试图阻止用户在某些情况下使用输入,但如果我向其添加disabled
,则无论其值是true
还是false
,都将禁用输入.
这是我的代码:
@Html.TextBoxFor(model => model.inputName, new { @disabled = (condition ? "true" : "false") })
在任何情况下,它都将被禁用.
我试图阻止用户在某些情况下使用输入,但如果我向其添加disabled
,则无论其值是true
还是false
,都将禁用输入.
这是我的代码:
@Html.TextBoxFor(model => model.inputName, new { @disabled = (condition ? "true" : "false") })
在任何情况下,它都将被禁用.
因为是否禁用取决于disabled
属性而不是disabled
属性值
下面是一个例子
<p>Last name: <input type="text" name="lname" disabled="" /></p>
<p>Last name: <input type="text" name="lname" disabled="true" /></p>
<p>Last name: <input type="text" name="lname" disabled="false" /></p>
如果你不想用Js来控制你的属性,我们可以判断if
条件为真,以创建disabled
的元素,否则就不是了.
@if(condition)
{
Html.TextBoxFor(model => model.inputName, new { @disabled = "true" })
}
else
{
Html.TextBoxFor(model => model.inputName)
}
否则我们可以为此创建一个扩展方法.
public static class TextBoxForExtensions
{
public static IHtmlString TextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
object htmlAttributes,
bool disabled
)
{
var attributes = new RouteValueDictionary(htmlAttributes);
if (disabled)
{
attributes["disabled"] = "disabled";
}
return htmlHelper.TextBoxFor(expression, attributes);
}
}
然后我们可以使用
@Html.TextBoxFor(model => model.inputName, new{},condition)