从Controller获取MVC2模型属性值

时间:2012-04-19 03:52:16

标签: c# asp.net asp.net-mvc-2

您好我想知道是否有一种直接的方法来检索我的模型中的自定义属性的值与控制器。为了节俭...让我说我的模型中有这个:

[DisplayName("A name")]
public string test;

在我的控制器中,我想通过使用与此类似的东西来检索“名称”:

ModelName.test.Attributes("DisplayName").value

这是一种幻想吗?

提前致谢。
WML

3 个答案:

答案 0 :(得分:3)

Here is a good article on how to retrieve values from attributes.我认为除了反思之外还有其他方法可以做到这一点。

从文章中(只需更改示例的属性类型:)):

   public static void PrintAuthorInfo(Type t) 
   {
      Console.WriteLine("Author information for {0}", t);
      Attribute[] attrs = Attribute.GetCustomAttributes(t);
      foreach(Attribute attr in attrs) 
      {
         if (attr is Author) 
         {
            Author a = (Author)attr;
            Console.WriteLine("   {0}, version {1:f}",
a.GetName(), a.version);
         }
      }
   }

答案 1 :(得分:1)

试试这个:

var viewData = new ViewDataDictionary<MyType>(/*myTypeInstance*/);
string testDisplayName = ModelMetadata.FromLambdaExpression(t => t.test, viewData).GetDisplayName();

答案 2 :(得分:1)

反射很容易。 内部控制器:

 public void TestAttribute()
    {
        MailJobView view = new MailJobView();
        string displayname = view.Attributes<DisplayNameAttribute>("Name") ;


    }

扩展:

   public static class AttributeSniff
{
    public static string Attributes<T>(this object inputobject, string propertyname) where T : Attribute
    {
        //each attribute can have different internal properties
        //DisplayNameAttribute has  public virtual string DisplayName{get;}
        Type objtype = inputobject.GetType();
        PropertyInfo propertyInfo = objtype.GetProperty(propertyname);
        if (propertyInfo != null)
        {
            object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(T), true);

            // take only publics and return first attribute
            if (propertyInfo.CanRead && customAttributes.Count() > 0)
            {
                //get that first one for now

                Type ourFirstAttribute = customAttributes[0].GetType();
                //Assuming your attribute will have public field with its name
                //DisplayNameAttribute will have DisplayName property
                PropertyInfo defaultAttributeProperty = ourFirstAttribute.GetProperty(ourFirstAttribute.Name.Replace("Attribute",""));
                if (defaultAttributeProperty != null)
                {
                    object obj1Value = defaultAttributeProperty.GetValue(customAttributes[0], null);
                    if (obj1Value != null)
                    {
                        return obj1Value.ToString();
                    }
                }

            }

        }

        return null;
    }

}

我测试它工作正常。它将使用该属性的第一个属性。 MailJobView类有一个名为“Name”的属性,带有DisplayNameAttribute。

相关问题