【发布时间】:2018-11-16 23:50:50
【问题描述】:
我正在使用 C# 4.5 和 ASP.NET MVC 5。 我有以下内容:
[Required(ErrorMessage = "Prop1 is required")]
public string Prop1 { get;set;}
[Required(ErrorMessage = "Prop2 is required")]
public string Prop2 { get;set;}
如您所见,错误消息是属性名称加上“是必需的”字符串。我需要的不是为每个属性键入属性名称和消息,而是使用通用方法作曲家,它将返回修饰属性的名称和我添加的字符串,例如:
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;}
简而言之:我如何知道由属性修饰的属性名称。
【问题讨论】:
-
这是不可能的 - 属性是元数据,必须在编译磁贴处知道。但你只需要
ErrorMessage = "{0} is required" -
这就是我想要的,谢谢
标签: c# asp.net asp.net-mvc asp.net-mvc-4 web