如何在MVC使用LabelFor插入换行符 [英] How to Insert Line Break using LabelFor in MVC

查看:1651
本文介绍了如何在MVC使用LabelFor插入换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的模型:

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

和我使用

@Html.LabelFor(shop => shop.IsLimitedQuantity) 

在我的视野。

请建议我怎么能解决这个问题,因为标签只是显示&LT;盈亏>,因为它是不是突破到一个新行,

Please suggest how I can fix this, because the label is just showing <break> as it is, instead of breaking to a new line.

推荐答案

您可以编写一个自定义的 LabelFor 帮助它不带HTML code中的文本不标准的 LabelFor 助手:

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)

现在的显示名称的HTML标签将不经过编码而呈现:

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

这篇关于如何在MVC使用LabelFor插入换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆