我有一个从EF4生成的部分类,我分配了一个MetadataType,以便在ASP.NET MVC3表单上显示控件的名称,并且它按照预期工作。
我希望使用分配给每个属性的相同的DisplayAttribute来为该属性提取显示的Name值,以达到另一目的。我的课是这样的:
using Domain.Metadata;
namespace Domain
{
[MetadataType(typeof(ClassAMetada))]
public partial class ClassA
{}
}
namespace Domain.Metadata
{
public class ClassAMetada
{
[Display(Name = "Property 1 Description", Order = 1)]
public Boolean Property1;
[Display(Name = "Property 2 Description", Order = 2)]
public Boolean Property2;
}
}我已经看到了这3篇文章,并尝试了下面的解决方案:
但是它们都不能撤回属性Name值;属性没有找到,因此是null,因此它返回一个空字符串(第三个问题)或属性名(第一个问题);第二个问题被轻描淡写地更改以发现属性,但结果也是一个空字符串。
你能帮我弄一下这个吗?非常感谢!
编辑:
下面是用于提取属性值的两个方法的代码(这两个方法分别工作)。两者非常相似:第一个使用带有属性名称的字符串,另一个使用lamba表达式。
private static string GetDisplayName(Type dataType, string fieldName)
{
DisplayAttribute attr;
attr = (DisplayAttribute)dataType.GetProperty(fieldName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault();
if (attr == null)
{
MetadataTypeAttribute metadataType = (MetadataTypeAttribute)dataType.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault();
if (metadataType != null)
{
var property = metadataType.MetadataClassType.GetProperty(fieldName);
if (property != null)
{
attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault();
}
}
}
return (attr != null) ? attr.Name : String.Empty;
}
private static string GetPropertyName<T>(Expression<Func<T>> expression)
{
MemberExpression propertyExpression = (MemberExpression)expression.Body;
MemberInfo propertyMember = propertyExpression.Member;
Object[] displayAttributes = propertyMember.GetCustomAttributes(typeof(DisplayAttribute), true);
if (displayAttributes != null && displayAttributes.Length == 1)
return ((DisplayAttribute)displayAttributes[0]).Name;
return propertyMember.Name;
}发布于 2011-04-27 11:08:14
您考虑过将显示名称放入资源中吗?它比所有这些反射魔法更容易重用。
你可以简单地做:
[Display(Name = "Property1Name", ResourceType = typeof(Resources), Order = 1)]
public Boolean Property1;并使用Resources.resx键和“Property1Description”值向项目添加Property1Name文件。当然,您可能必须将默认资源访问从internal设置为public。
稍后,在其他地方,只需调用这些字符串:
string displayName = Domain.Resources.Property1Name;https://stackoverflow.com/questions/5802228
复制相似问题