Peter
Peter

Reputation: 21

Overwrite TextBoxFor Helper in ASP.NET MVC with HtmlAttributes

Am Trying to use custom TextBoxFor in ASP.NET MVC 3 to change some existing attributes.

While rendering,

@Html.MYTextBoxFor(model => model.FirstName, new { @class = "textfield", @tabindex = "1", @maxlength = "50", @size = "30" })

But it ignores the htmlAttributes(tabindex,maxlength,size).

public static MvcHtmlString MYTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
    string elementName = ExpressionHelper.GetExpressionText(expression);               

    MvcHtmlString normal = html.TextBoxFor(expression);
    if (normal != null)
    {
        string newValidator = normal.ToHtmlString();                
        newValidator = newValidator.Replace("data-val-required", "databvalidatormsg");
        return MvcHtmlString.Create(newValidator);
    }
    return null;
}

Upvotes: 2

Views: 2382

Answers (1)

fearofawhackplanet
fearofawhackplanet

Reputation: 53456

Well, you're not using your htmlAttributes arg anywhere in the function.

Don't you need something like...

MvcHtmlString normal = html.TextBoxFor(expression, htmlAttributes);

Also, you don't need the @ char infront of the tabindex, maxlength and size attributes.

Upvotes: 2

Related Questions