How to Insert Line Break using LabelFor in MVC

后端 未结 2 717
死守一世寂寞
死守一世寂寞 2021-01-15 04:15

I have in my Model:

[Display(Name = \"Check to enter  the Quantity of items\")]
public bool IsLimitedQuantity { get; set; }

an

相关标签:
2条回答
  • 2021-01-15 04:50

    You could write a custom LabelFor helper which doesn't HTML encode the text as does the standard LabelFor helper:

    public static class LabelExtensions
    {
        public static IHtmlString UnencodedLabelFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            var htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            var text = (metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last<string>()));
            if (string.IsNullOrEmpty(text))
            {
                return MvcHtmlString.Empty;
            }
            var tagBuilder = new TagBuilder("label");
            tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
            tagBuilder.InnerHtml = text;
            return new HtmlString(tagBuilder.ToString(TagRenderMode.Normal));
        }
    }
    

    and then use this custom helper in the view:

    @Html.UnencodedLabelFor(x => x.IsLimitedQuantity)
    

    Now the HTML tags in the display name will be rendered without encoding:

    [Display(Name = "Check to enter <br/> the Quantity of items")]
    public bool IsLimitedQuantity { get; set; }
    
    0 讨论(0)
  • 2021-01-15 05:07

    Using Html decode may help. MVC for security reasons encode all the values.

    How to display HTML stored in a database from an ASP.NET MVC view?

    0 讨论(0)
提交回复
热议问题