如何在MVC中使用LabelFor插入换行符

Ume*_* K. 2 asp.net-mvc line-breaks

我的模型中有:

[Display(Name = "Check to enter <break> the Quantity of items")]
public bool IsLimitedQuantity { get; set; }
Run Code Online (Sandbox Code Playgroud)

我正在使用

@Html.LabelFor(shop => shop.IsLimitedQuantity) 
Run Code Online (Sandbox Code Playgroud)

在我看来.

请建议我如何解决这个问题,因为标签只是按原样显示<break>,而不是打破新行.

Dar*_*rov 8

您可以编写一个自定义LabelFor帮助程序,它不像标准LabelFor帮助程序那样对文本进行HTML编码:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在视图中使用此自定义帮助程序:

@Html.UnencodedLabelFor(x => x.IsLimitedQuantity)
Run Code Online (Sandbox Code Playgroud)

现在,显示名称中的HTML标记将在不进行编码的情况下呈现:

[Display(Name = "Check to enter <br/> the Quantity of items")]
public bool IsLimitedQuantity { get; set; }
Run Code Online (Sandbox Code Playgroud)