Can anyone provide a straight forward example to extend the Html.TextBoxFor helper
I'm hoping that someone can provide a simple, straight forward example of extending the Html.TextBoxFor helper. I would like to include a boolean ReadOnly parameter which will (surp开发者_如何学编程rise, surprise, surprise) render the control read only if true. I've seen a few examples which didn't quite do the trick and I've tried the following however, the only signature for TextBoxFor that the HtmlHelper parameter sees is the one I'm creating (am I missing a using statement?):
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, bool disabled)
{
var values = new RouteValueDictionary(htmlAttributes);
if (disabled)
values.Add("disabled", "true");
return htmlHelper.TextBoxFor(expression, values)); //<-- error here
}
I'm hoping that a simple example will help get me on the right track.
Thanks.
make sure you're using System.Web.Mvc.Html;
in your extension class to call HtmlHelper.TextBoxFor<>
.
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
object htmlAttributes,
bool disabled)
{
var values = new RouteValueDictionary(htmlAttributes);
// might want to just set this rather than Add() since "disabled" might be there already
if (disabled) values["disabled"] = "true";
return htmlHelper.TextBoxFor<TModel, TProperty>(expression, htmlAttributes);
}
You have one opening and two closing parenthesis on this line. Should be:
return htmlHelper.TextBoxFor(expression, values);
Also to make your HTML a little more standards friendly:
values["disabled"] = "disabled";
精彩评论