我試圖阻止用戶在某些情況下使用輸入,但是如果我添加disabled
它來禁用它,無論它的值為true
or ,它都會禁用false
。
這是我的代碼:
@Html.TextBoxFor(model => model.inputName, new { @disabled = (condition ? "true" : "false") })
在任何情況下,它將被禁用。
uj5u.com熱心網友回復:
正如我在對此問題的評論中所說,您可以添加變數:
var myAttributes = condition ? new {@disabled = true, /* add some more here*/} : new {/*add more here*/}
然后你可以將它添加到你的助手中:
@Html.TextBoxFor(model => model.inputName, myAttributes)
uj5u.com熱心網友回復:
因為是否禁用取決于您的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
條件判斷為 true 來創建元素,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);
}
}
然后我們可以使用like
@Html.TextBoxFor(model => model.inputName, new{},condition)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/466779.html