Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to overload Html.LabelFor to add a 'suffix'?

I would like to add an extension to html.labelfor, so that I could use something like:

@Html.LabelFor(m=>m.Description, ":")

Which would add the semicolon as a suffix in the rendered HTML:

Description:

like image 820
Kman Avatar asked Sep 02 '14 13:09

Kman


1 Answers

You could do this:

@Html.LabelFor(m => m.Description,
               string.Format("{0}:", Html.DisplayNameFor(m => m.Description)))

DisplayNameFor gives you just the display name for the property without the label markup, so you can use this as part of the labelText parameter in LabelFor and format it as you please. This way you still get the benefit of dynamically generated label text.

Easily wrapped up in its own helper:

public static MvcHtmlString LabelWithColonFor<TModel, TValue>(
              this HtmlHelper<TModel> helper,
              Expression<Func<TModel, TValue>> expression)
{
    return helper.LabelFor(expression, string.Format("{0}:",
                                              helper.DisplayNameFor(expression)));
}

Then:

@Html.LabelWithColonFor(m => m.Description)
like image 106
Ant P Avatar answered Sep 28 '22 18:09

Ant P