How can I add inline html elements inside a label with Html.Label?
In order to meet the SOC and Solid principles, the code can be enhanced to the following code:
public static MvcHtmlString LabelFor(this HtmlHelper htmlHelper, Expression> ex,bool applyStylingHtml)
{
var metadata = ModelMetadata.FromLambdaExpression(ex, htmlHelper.ViewData);
string displayName = metadata.DisplayName;
string description= metadata.Description;
if (String.IsNullOrEmpty(displayName))
{
return MvcHtmlString.Empty;
}
var sb = new StringBuilder();
sb.Append(displayName);
var htmlFieldName = ExpressionHelper.GetExpressionText(ex);
var propertyName = htmlFieldName.Split('.').Last();
var tag = new TagBuilder("label");
tag.Attributes["for"] = TagBuilder.CreateSanitizedId(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName));
tag.SetInnerText(sb.ToString());
//Func
Then use it in the Razor code:
@Html.LabelFor(m => m.Phone,true)
To make everything more dynamic, description attribute should be applied on the Model class then HtmlHelper will grab the Description as a text to be applied "em" Html tag:
[Display(Name ="Phone",Description = "should be included extention")]
public string Phone { get; set; }
Just a heads up that you need to import the your customized HtmlHelper namespace to the view by adding:
@using yourNamespace