Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I add inline html elements inside a label with Html.Label?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
383 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...