DisplayAttribute中的Html标签 [英] Html tags inside DisplayAttribute

查看:114
本文介绍了DisplayAttribute中的Html标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望显示名称包含一些html文本。



例如:

  [Display(Name =名字< b class = \red \>粗体文字< / b>)] 
公共字符串名字{get; set;}

但在浏览器的屏幕上,我看到:

名字< b class =red>粗体文字< / b>



而不是:

名字 boldtext



是否有任何事情可以使它与Display属性一起工作?



基本上,我希望在所有必需的属性之后显示红色*,或者如果这种方式无法正常工作,我可以更好地做到这一点吗?


<显示属性属于Model,所以它应该包含纯文本数据,不包含任何格式。

如果你想添加格式为name ,你可以像这样做


写一个扩展方法来从显示名称获得价值

  public static MvcHtmlString DisplayNameFor< TModel,TValue>(this HtmlHelper< TModel>表达式< Func< TModel,TValue>>表达式,字符串templateName)
{
表达式expressionBody = expression.Body;

if(expressionBody是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});


$ / code $ / pre

查看:

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

Template:_NameTemplate.cshtml

 < span> @ViewData [Message ] LT; /跨度> 

希望它对您有用


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?

解决方案

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

这篇关于DisplayAttribute中的Html标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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