Html tags inside DisplayAttribute

2019-04-13 06:25发布

问题:

I would like the display name to contain some html text.

For example something like:

[Display(Name = "First Name <b class=\"red\">boldtext</b>)]
public string FirstName { get; set; }

But on the browser's screen I see:

First Name <b class="red">boldtext</b>

Instead of:

First Name boldtext

Is there anything I can do to make it work with the Display attribute?

Basically I would like to display red * after all the required attributes, or is there some another way that I could do this better if this way is not able to work?

回答1:

Display property belong to Model, so it should contain plain text data, no any format.
If you want to add format to name, you can do like this
Write an extension method to get value from Display Name

    public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName)
    {
        Expression expressionBody = expression.Body;

        if (expressionBody is MemberExpression)
        {
            MemberExpression memberExpression = (MemberExpression)expressionBody;
            string propertyName = memberExpression.Member.Name;

            return html.DisplayFor(expression, templateName, new { Message = html.ViewData.ModelMetadata.Properties.Single(p => p.PropertyName == propertyName).Name});
        }            
    }

View:

@Html.DisplayNameFor(model => model.FirstName, "_NameTemplate")

Template: _NameTemplate.cshtml

<span>@ViewData["Message"]</span>

Hope it's useful for you



回答2:

You can create your own DisplayFor template to render this object with whatever template you like.