Html inside label using Html helper
Rather then writing an extension method you could use the following razor code:
@{ MvcHtmlString label = Html.LabelFor(m => m.ModelProperty, "<span class='cssClass'>Label HTML</span>", new { @class = "clabel"}); }
@Html.Raw(HttpUtility.HtmlDecode(label.ToString()))
It's not as clean but if you need something quick it works.
Looks like a good scenario for a custom helper:
public static class LabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> ex,
Func<object, HelperResult> template
)
{
var htmlFieldName = ExpressionHelper.GetExpressionText(ex);
var for = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName);
var label = new TagBuilder("label");
label.Attributes["for"] = TagBuilder.CreateSanitizedId(for);
label.InnerHtml = template(null).ToHtmlString();
return MvcHtmlString.Create(label.ToString());
}
}
and then:
@Html.LabelFor(
x => x.Name,
@<span>Hello World</span>
)
UPDATE:
To achieve what you asked in the comments section you may try the following:
public static class HtmlHelperExtensions
{
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex, Func<object, HelperResult> template)
{
var htmlFieldName = ExpressionHelper.GetExpressionText(ex);
var propertyName = htmlFieldName.Split('.').Last();
var label = new TagBuilder("label");
label.Attributes["for"] = TagBuilder.CreateSanitizedId(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName));
label.InnerHtml = string.Format(
"{0} {1}",
propertyName,
template(null).ToHtmlString()
);
return MvcHtmlString.Create(label.ToString());
}
}
and then:
@Html.LabelFor(
x => x.Name,
@<em>mandatory</em>
)