似乎是自定义助手的一个很好的候选者:
public static class HtmlExtensions
{
public static IHtmlString TextBoxFor(
this HtmlHelper htmlHelper,
Expression> ex,
object htmlAttributes,
bool disabled
)
{
var attributes = new RouteValueDictionary(htmlAttributes);
if (disabled)
{
attributes["disabled"] = "disabled";
}
return htmlHelper.TextBoxFor(ex, attributes);
}
}
可以像这样使用:
@Html.TextBoxFor(
m => m.PracticeName,
new { style = "width:100%" },
Model.PracticeName != String.Empty
)
帮助器显然可以更进一步,因此您不需要传递额外的布尔值,但它会自动确定表达式的值是否等于默认值(TProperty)并且它应用disabled属性.
另一种可能性是这样的扩展方法:
public static class AttributesExtensions
{
public static RouteValueDictionary DisabledIf(
this object htmlAttributes,
bool disabled
)
{
var attributes = new RouteValueDictionary(htmlAttributes);
if (disabled)
{
attributes["disabled"] = "disabled";
}
return attributes;
}
}
您将使用标准TextBoxFor帮助程序:
@Html.TextBoxFor(
m => m.PracticeName,
new { style = "width:100%" }.DisabledIf(Model.PracticeName != string.Empty)
)