任何方式风格的文本包含在DataAnnotation属性[显示(名称="文本和QUOT;)? [英] Any way to style text contained in DataAnnotation Attribute [Display(Name = "Text")]?
问题描述
我想要做这样的事情:
[显示(NAME =纯文字<跨度类= \\红强\\>红色文本加粗< / SPAN>中)
这是可能的(到样式的显示属性中的文本)?目前,它只是显示文字文本。
这是可能的(到样式的显示属性中的文字)?
块引用>问题不在于
[显示]
属性中。它位于您用来显示Html.LabelFor
助手里。此属性总是HTML EN codeS的值。如果你不喜欢这种行为,你可以写一个自定义帮手,不会带code的值:公共静态类HtmlExtensions
{
公共静态IHtmlString MyLabelFor<的TModel,TProperty>(
这与的HtmlHelper LT;的TModel>的HtmlHelper,
防爆pression<&Func键LT;的TModel,TProperty>>前pression
)
{
VAR元= ModelMetadata.FromLambdaEx pression<的TModel,TProperty>(例如pression,htmlHelper.ViewData);
VAR htmlFieldName =前pressionHelper.GetEx pressionText(如pression);
VAR LabelText的=(metadata.DisplayName ??(metadata.PropertyName ?? htmlFieldName.Split(新的char [] {'。'})上次<串GT;()));
如果(string.IsNullOrEmpty(LabelText的))
{
返回MvcHtmlString.Empty;
}
VAR标签=新TagBuilder(标签);
label.Attributes.Add(为 TagBuilder.CreateSanitizedId(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
label.InnerHtml = LabelText的;
返回新HtmlString(label.ToString()); }
}和则:
@ Html.MyLabelFor(X => x.Foo)
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.
解决方案Is this possible (to style the text within the Display Attribute)?
The problem doesn't lie within the
[Display]
attribute. It lies within theHtml.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)
这篇关于任何方式风格的文本包含在DataAnnotation属性[显示(名称=&QUOT;文本和QUOT;)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!