Easy way to overload Html.Label to add suffix?
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)
source to share
Here's a link to duplicate question and answer.
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.
source to share
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)}:")
source to share