问题
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