加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – asp.net MVC扩展DataAnnotions

发布时间:2020-12-16 06:36:31 所属栏目:asp.Net 来源:网络整理
导读:以及DisplayName例如. [DisplayName("Address line 1 ")]public string Address1{get; set;}Html.LabelFor(model = model.Address1) 我需要显示工具提示,例如. [DisplayName("Address line 1 ")][ToolTip("The first line of your address as it appears on
以及DisplayName例如.

[DisplayName("Address line 1 ")]
public string Address1{get; set;}

Html.LabelFor(model => model.Address1)

我需要显示工具提示,例如.

[DisplayName("Address line 1 ")]
[ToolTip("The first line of your address as it appears on you bank statement")]
public string Address1{get; set;}

Html.LabelFor(model => model.Address1) 
Html.ToolTipFor(model => model.Address1)

我可以扩展DisplayName DataAnnotation来执行此操作吗?我看不出它是如何完成的.

谢谢!

解决方法

我就是这样做的.一些欧洲冠军联赛的时间,如果你愿意,我明天可以澄清代码.

首先是一个属性:

public class TooltipAttribute : DescriptionAttribute
{
    public TooltipAttribute()
        : base("")
    {

    }

    public TooltipAttribute(string description)
        : base(description)
    {

    }
}

然后是一个html帮助器,允许我们编写Html.TooltipFor():

public static class HtmlHelpers
{
    public static MvcHtmlString ToolTipFor<TModel,TValue>(this HtmlHelper<TModel> html,Expression<Func<TModel,TValue>> expression)
    {
        var exp = (MemberExpression)expression.Body;
        foreach (Attribute attribute in exp.Expression.Type.GetProperty(ex.Member.Name).GetCustomAttributes(false))
        {
            if (typeof(TooltipAttribute) == attribute.GetType())
            {
                return MvcHtmlString.Create(((TooltipAttribute)attribute).Description);
            }
        }
        return MvcHtmlString.Create("");
    }
}

用法就是:

你的型号:

public class User
{
    [Tooltip("This is the attribute for FirstName")]
    public string FirstName { get; set; }
}

在你看来:

<%= Html.ToolTipFor(x => x.FirstName) %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读