Html inside label using Html helper

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

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

5条回答
  •  不思量自难忘°
    2020-12-03 11:55

    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 template='';
            HtmlString nestedHtml=new HtmlString(""+description+"");
            tag.InnerHtml = string.Format(
                "{0} {1}",
                tag.InnerHtml,
               nestedHtml
            );
    
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
    

    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
    

提交回复
热议问题