Any way to style text contained in DataAnnotation Attribute [Display(Name = “Text”)]?

假装没事ソ 提交于 2019-12-12 10:27:27

问题


I want to do something like this:

[Display(Name = "Plain text. <span class=\"red strong\">Red text bolded.</span>")]

Is this possible (to style the text within the Display Attribute)? Currently it is just displaying the literal text.


回答1:


Is this possible (to style the text within the Display Attribute)?

The problem doesn't lie within the [Display] attribute. It lies within the Html.LabelFor helper which you used to display. This attribute always HTML encodes the value. If you don't like this behavior you could write a custom helper that will not encode the value:

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

    }
}

and then:

@Html.MyLabelFor(x => x.Foo)


来源:https://stackoverflow.com/questions/9809223/any-way-to-style-text-contained-in-dataannotation-attribute-displayname-tex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!