似乎是一个很好的候选人定制的帮手:
public static class HtmlExtensions
{
public static IHtmlString TextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> 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
)
助手可以明显地采取更进一步,因此您不需要传递额外的布尔值,但它会自动确定表达式的值是否等于default(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)
)
谢谢,我用了第二种扩展方法,太棒了! –