[英]Get MVC2 model attribute value from Controller
Hi I am wondering if there is a straight forward way to retrieve the value of a custom attribute in my model VIA a controller. 嗨,我想知道是否有一种简单的方法可以通过控制器在我的模型中检索自定义属性的值。 For arugment sake...let's say I have this in my model:
出于粗略的考虑...假设我的模型中有这个:
[DisplayName("A name")]
public string test;
In my controller I want to retrieve "A name" by using something similar to this: 在我的控制器中,我想通过使用类似于以下内容的方法来检索“ A名称”:
ModelName.test.Attributes("DisplayName").value
Is it something fanciful? 有什么幻想吗?
Thanks in advance. 提前致谢。
WML WML
Here is a good article on how to retrieve values from attributes. 这是一篇有关如何从属性检索值的好文章。 I don't think there is any other way to do this beyond reflection.
我认为没有其他方法可以做到这一点。
From the article (just change the Attribute type for your example :)): 在文章中(只需更改示例的Attribute类型:)):
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);
}
}
}
Try this: 尝试这个:
var viewData = new ViewDataDictionary<MyType>(/*myTypeInstance*/);
string testDisplayName = ModelMetadata.FromLambdaExpression(t => t.test, viewData).GetDisplayName();
It is easy to do with reflection. 反射很容易做到。 Inside controller:
内部控制器:
public void TestAttribute()
{
MailJobView view = new MailJobView();
string displayname = view.Attributes<DisplayNameAttribute>("Name") ;
}
Extension: 延期:
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;
}
}
I tested it works fine. 我测试它工作正常。 It will use first attribute on that property.
它将在该属性上使用第一个属性。 MailJobView class has a property named "Name" with DisplayNameAttribute.
MailJobView类具有一个带DisplayNameAttribute的名为“ Name”的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.