我使用的是C# 4.5和ASP.NET MVC5。我有以下内容:
[Required(ErrorMessage = "Prop1 is required")]
public string Prop1 { get;set;}
[Required(ErrorMessage = "Prop2 is required")]
public string Prop2 { get;set;}
正如您所看到的,错误消息是属性名称加上“is required”字符串。我需要的不是为每个属性键入属性名称和消息,而是使用泛型方法编写器,它将返回装饰属性的名称和我添加的字符串,如下所示:
public string GetMessage()
{
// Caller property should be a variable that is retrieved dynamically
// that holds the name of the property that called the function
return CallerProperty + " is required";
}
所以现在我可以使用:
[Required(ErrorMessage = GetMessage())]
public string Prop2 { get;set;}
所以简而言之:我如何知道由属性修饰的属性名称。
https://stackoverflow.com/questions/50734871
复制相似问题