我想基于布尔值禁用或启用文本框,我创建了此扩展方法:
public static IHtmlString MyTextBoxFor(
this HtmlHelper htmlHelper,
Expression> expression,
object htmlAttributes,
bool disabled
)
{
var attributes = new RouteValueDictionary(htmlAttributes);
if (disabled)
{
attributes.Add("disabled", "\"disabled\"");
}
return htmlHelper.TextBoxFor(expression, htmlAttributes);
}
那就是我的用法:
@Html.MyTextBoxFor(model => model.Body, new { @class = "form-control"}, true)
但是它不起作用,我不熟悉Htmlhelper类,虽然不难理解,但是我确实错过了一些东西!
编辑:
我尝试了这种简单的方法,以找出问题所在:
public static IHtmlString MyTextBox(this HtmlHelper htmlHelper,object htmlAttributes, bool disabled)
{
IDictionary attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
//var attrs = new Dictionary();
if (disabled)
{
attrs.Add("disabled", "disabled");
attrs.Add("value", "txxxxxxt");
}
return htmlHelper.TextBox("txtbx", attrs);
}
并且已经呈现出来: