Easy way to overload Html.Label to add suffix?

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

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

      

To add a semicolon as a suffix in the rendered HTML:

Description:

+3


source to share


3 answers


You can do it:

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

      

DisplayNameFor

gives you only the display name of the property, no label markup, so you can use that as part of the parameter labelText

in LabelFor

and format it however you like. This way you still benefit from the dynamically generated shortcut text.

Easily wrapped in your 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)

      

+10


source


Here's a link to duplicate question and answer.

Postfix label text with colon



This is good because the colon is really a design element and not part of the displayModel displayname attribute. This is good because the colon will appear in any validation message that uses the diaplayname attribute

And the css is very simple.

0


source


In .NET 4.6+, you can use interpolated strings :

<label>@($"{Html.DisplayNameFor(m => m.Description)}:")</label>

      

Or if you prefer the extended version

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

      

0


source







All Articles