0

I want to write my own custom HTML helper that extends an existing helper. E.g. I want to create to extend @Html.EditorFor like so:

@Html.EditorFor(model => model.percent, new { data_a_sign="%", data_p_sign="s" })

Becomes:

@Html.PercentEditorFor(model => model.percent)

How would one go about writing that?

Something like this?

namespace AdminPortal.Helpers
{
    public static class HtmlHelpers
    {
        public static MvcHtmlString PercentEditorFor<TModel>(this HtmlHelper html, 
            Expression<Func<TModel>> expression)
        {
            // Some Magic?
        }
    }
}

Any pointers would be greatly appreciated.

Martinffx
  • 2,426
  • 4
  • 33
  • 60

1 Answers1

1

It's just a matter of returning the existing EditorFor method from your own helper:

public static MvcHtmlString PercentEditorFor<TModel>(this HtmlHelper html, 
            Expression<Func<TModel>> expression)
        {
            return html.EditorFor(...);
        }

Put your own modified parameters into the EditorFor method. No magic required :)

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • Thanks, but I think I've misunderstood my problem. I want to add custom class and data attributes to the input generated by `@Html.EditorFor`, but when I add those attributes they are ignored by the template. – Martinffx Jul 19 '13 at 09:07
  • I've asked the new question here: http://stackoverflow.com/questions/17742488/how-to-add-custom-data-attributes-and-classes-to-html-editorfor – Martinffx Jul 19 '13 at 09:23