Asp.net-Mvc-3

使用 Html 助手的 Html 內部標籤

  • April 20, 2020

如何使用 Html.Label 在標籤內添加內聯 html 元素?

對於自定義助手來說,這似乎是一個很好的場景:

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());
   }
}

然後:

@Html.LabelFor(
   x => x.Name, 
   @<span>Hello World</span>
)

更新:

要實現您在評論部分中提出的要求,您可以嘗試以下操作:

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());
   }
}

然後:

@Html.LabelFor(
   x => x.Name, 
   @<em>mandatory</em>
)

引用自:https://stackoverflow.com/questions/5706815