Mr Bell
Mr Bell

Reputation: 9338

How to extend/override mvc html.LabelFor

I have an overload for LabelFor that can be used like this:

@Html.LabelFor(i => i.MyProperty)

How can I get the compiler to use my overload instead of the one provided by MVC ootb?

Basically this is just so that I can have required fields label's spit out with * suffix

Upvotes: 3

Views: 1724

Answers (2)

Matthew Abbott
Matthew Abbott

Reputation: 61589

LabelFor accepts an Expression<Func<TModel, TValue>> parameter. I would imagine you could do something like:

public static string LabelFor<TModel, string>(
    this HtmlHelper<TModel> htmLHelper, 
    Expression<Func<TModel, string>> expression) {
    // etc

... to make your extension method overload more specific, but that doesn't mean you should, as you would need to do so for all property types.

Rather than have your method naming get mixed up with the standard HtmlHelper extension methods, name it differently, e.g.

@Html.MyLabelFor(m => m.MyProperty);

Upvotes: 1

Chris Marisic
Chris Marisic

Reputation: 33098

For that overload, you can't (reasonably).

Just name the method Label() or MyLabelFor() etc.

Upvotes: 4

Related Questions