使用 @SLaks 建議使用一個擴展方法,並使用耶利米克拉克的例子擴展方法我寫了所以我現在可以做一個擴展方法Html.TextBoxFor(m => m.FirstName,new{class='contactDetails',.. .},Page.User.IsInRole("administrator"));
不知道是否有更好的方法public static class InputExtensions
{
public static IDictionary TurnObjectIntoDictionary(object data)
{
var attr = BindingFlags.Public | BindingFlags.Instance;
var dict = new Dictionary();
if (data == null)
return dict;
foreach (var property in data.GetType().GetProperties(attr))
{
if (property.CanRead)
{
dict.Add(property.Name, property.GetValue(data, null));
}
}
return dict;
}
public static MvcHtmlString TextBoxFor(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes, bool disabled)
{
IDictionary values = TurnObjectIntoDictionary(htmlAttributes);
if (disabled)
values.Add("disabled","true");
return htmlHelper.TextBoxFor(expression, values);
}
public static MvcHtmlString TextAreaFor(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes, bool disabled)
{
IDictionary values = TurnObjectIntoDictionary(htmlAttributes);
if (disabled)
values.Add("disabled","true");
return htmlHelper.TextAreaFor(expression, values);
}
public static MvcHtmlString CheckBoxFor(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes, bool disabled)
{
IDictionary values = TurnObjectIntoDictionary(htmlAttributes);
if (disabled)
values.Add("disabled","true");
return htmlHelper.CheckBoxFor(expression, values);
}
}