Reputation: 573
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 (surprise, 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.
Upvotes: 2
Views: 1383
Reputation: 1039508
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";
Upvotes: 1
Reputation: 63562
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);
}
Upvotes: 2