获取MVC3服务器端code显示注释值 [英] Get display annotation value on mvc3 server side code

查看:130
本文介绍了获取MVC3服务器端code显示注释值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让服务器端code注释的价值?例如,我有:

Is there a way to get the value of an annotation in server side code? For example, I have:

public class Dummy
{
    [Display(Name = "Foo")]
    public string foo { get; set; }

    [Display(Name = "Bar")]
    public string bar { get; set; }
}

我希望能够得到与出张贴回到页面服务器端值,但像那种类的属性,什么的。像 @ Html.LabelFor(型号=> model.Foo)但在C#服务器code。

I want to be able to get the value "Foo" on server side with out posting it back to the page, but like an attribute of the class, or something of the sort. Like a @Html.LabelFor(model => model.Foo) But in c# server code.

这可能吗?

感谢您。

推荐答案

这样呢?

string displayName = GetDisplayName((Dummy x) => x.foo);

// ...

public static string GetDisplayName<T, U>(Expression<Func<T, U>> exp)
{
    var me = exp.Body as MemberExpression;
    if (me == null)
        throw new ArgumentException("Must be a MemberExpression.", "exp");

    var attr = me.Member
                 .GetCustomAttributes(typeof(DisplayAttribute), false)
                 .Cast<DisplayAttribute>()
                 .SingleOrDefault();

    return (attr != null) ? attr.Name : me.Member.Name;
}

或者,如果你希望能够调用该方法针对一个实例,并采取类型推断的优势:

Or, if you want to be able to call the method against an instance and take advantage of type inference:

var dummy = new Dummy();
string displayName = dummy.GetDisplayName(x => x.foo);

// ...

public static string GetDisplayName<T, U>(this T src, Expression<Func<T, U>> exp)
{
    var me = exp.Body as MemberExpression;
    if (me == null)
        throw new ArgumentException("Must be a MemberExpression.", "exp");

    var attr = me.Member
                 .GetCustomAttributes(typeof(DisplayAttribute), false)
                 .Cast<DisplayAttribute>()
                 .SingleOrDefault();

    return (attr != null) ? attr.Name : me.Member.Name;
}

这篇关于获取MVC3服务器端code显示注释值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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