asp.net MVC扩展DataAnnotions [英] asp.net MVC extending DataAnnotions

查看:116
本文介绍了asp.net MVC扩展DataAnnotions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如DisplayName.

As well as DisplayName eg.

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

Html.LabelFor(model => model.Address1) 

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

I have a requirement to show tooltips eg.

[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来做到这一点吗?我不知道该怎么办.

Can I extend the DisplayName DataAnnotation to do this? I can't see how it can be done.

谢谢!

推荐答案

这就是我的方法.是时候参加欧洲冠军联赛了,如果您愿意的话,我明天可以澄清代码.

This is how I would do it. Time for some Champions League, I can clarify the code tomorrow if you want.

第一个属性:

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

    }

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

    }
}

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

And then a html helper to allow us to write 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) %>

这篇关于asp.net MVC扩展DataAnnotions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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