views:

128

answers:

2

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.

+2  A: 

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);
    }
hunter
Thanks, hunter. I thought it was a missing namespace. For other newbie web developers like myself be sure to add the namespace for your extended helper to your web.config as well (system.web/pages/namespaces).
fynnbob
+1  A: 

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";
Darin Dimitrov
Thanks, Darin. The extra bracket was a typo. The problem was due to missing the namespace for System.Web.Mvc.Html.
fynnbob