Html inside label using Html helper

后端 未结 5 1247
甜味超标
甜味超标 2020-12-03 11:14

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

5条回答
  •  难免孤独
    2020-12-03 12:16

    Looks like a good scenario for a custom helper:

    public static class LabelExtensions
    {
        public static MvcHtmlString LabelFor(
            this HtmlHelper htmlHelper, 
            Expression> ex, 
            Func 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, 
        @Hello World
    )
    

    UPDATE:

    To achieve what you asked in the comments section you may try the following:

    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString LabelFor(this HtmlHelper htmlHelper, Expression> ex, Func 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, 
        @mandatory
    )
    

提交回复
热议问题