kooldave98..
10
这已经晚了,但可能对某些人有所帮助.
我已经扩展了@ DarinDimitrov的答案,允许传递第二个对象,它接受任意数量的布尔html属性等disabled="disabled" checked="checked", selected="selected".
仅当属性值为true时才会呈现属性,其他任何内容和属性都不会呈现.
自定义可重用的HtmlHelper:
public static class HtmlExtensions
{
public static IHtmlString MyTextBoxFor(this HtmlHelper htmlHelper,
Expression> expression,
object htmlAttributes,
object booleanHtmlAttributes)
{
var attributes = new RouteValueDictionary(htmlAttributes);
//Reflect over the properties of the newly added booleanHtmlAttributes object
foreach (var prop in booleanHtmlAttributes.GetType().GetProperties())
{
//Find only the properties that are true and inject into the main attributes.
//and discard the rest.
if (ValueIsTrue(prop.GetValue(booleanHtmlAttributes, null)))
{
attributes[prop.Name] = prop.Name;
}
}
return htmlHelper.TextBoxFor(expression, attributes);
}
private static bool ValueIsTrue(object obj)
{
bool res = false;
try
{
res = Convert.ToBoolean(obj);
}
catch (FormatException)
{
res = false;
}
catch(InvalidCastException)
{
res = false;
}
return res;
}
}
您可以这样使用:
@Html.MyTextBoxFor(m => Model.Employee.Name
, new { @class = "x-large" , placeholder = "Type something…" }
, new { disabled = true})