[英]asp.net mvc2 - how to get model and model.something in the same way in controller?
[英]Get MVC2 model attribute value from Controller
嗨,我想知道是否有一种简单的方法可以通过控制器在我的模型中检索自定义属性的值。 出于粗略的考虑...假设我的模型中有这个:
[DisplayName("A name")]
public string test;
在我的控制器中,我想通过使用类似于以下内容的方法来检索“ A名称”:
ModelName.test.Attributes("DisplayName").value
有什么幻想吗?
提前致谢。
WML
这是一篇有关如何从属性检索值的好文章。 我认为没有其他方法可以做到这一点。
在文章中(只需更改示例的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);
}
}
}
尝试这个:
var viewData = new ViewDataDictionary<MyType>(/*myTypeInstance*/);
string testDisplayName = ModelMetadata.FromLambdaExpression(t => t.test, viewData).GetDisplayName();
反射很容易做到。 内部控制器:
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类具有一个带DisplayNameAttribute的名为“ Name”的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.