我的视图模型中有以下代码正常工作,并在我的视图上放置验证消息:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield return new ValidationResult("Required", new[] { "Insured.FirstName" });
}
但是,我想在不使用字符串文字的情况下引用成员名称,所以我尝试将其更改为以下内容:
yield return new ValidationResult("Required", new[] { nameof(Insured.FirstName) });
这不起作用。验证消息未出现在我的视图中。这是不支持还是我做错了?
答案 0 :(得分:0)
感谢上面的评论,我最终把它放在了Utilities类中:
public static class Utilities
{
public static string GetPathOfProperty<T>(Expression<Func<T>> property)
{
string resultingString = string.Empty;
var p = property.Body as MemberExpression;
while (p != null)
{
resultingString = p.Member.Name + (resultingString != string.Empty ? "." : "") + resultingString;
p = p.Expression as MemberExpression;
}
return resultingString;
}
}
然后我可以执行以下操作:
yield return new ValidationResult("Required", new[] { Utilities.GetPathOfProperty(() => Insured.FirstName) });