【发布时间】:2014-08-22 15:34:06
【问题描述】:
我使用的是实体框架代码优先方法,这意味着我的模型需要数据注释属性来创建数据库。我确实希望验证在我的模型上。
我的网站上有一些观点可以发布一些信息。但这些信息并不是整个模型,如果我要验证它,验证就会失败。
例如,我可以有一个具有这些 必需 属性的模型:Title、Text、X... 但是我可以有一个视图,它只会发布Text。为此,我正在创建一个 ViewModel(其中还有其他未附加到模型的元素)。但是在这种情况下我将如何验证Text?我需要它与模型属性Text 具有相同的验证。
有没有办法在不重复代码的情况下对模型和视图模型进行相同的验证?
这种尝试根本行不通……
我想创建一个自定义属性,将验证链接到模型:
/* This wouldn't work */
public class PropertyValidationAttribute : ValidationAttribute
{
public Type Type { get; set; }
public string PropertyName { get; set; }
public PropertyValidationAttribute(Type type, string propertyName)
{
Type = type;
PropertyName = propertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var attrs = Type.GetProperty(PropertyName).GetCustomAttributes(typeof(ValidationAttribute), true) as IEnumerable<ValidationAttribute>;
if (attrs != null)
{
foreach (var attr in attrs)
{
return attr.GetValidationResult(value, validationContext);
}
}
return base.IsValid(value, validationContext);
}
}
上面的问题是每个ValidationAttribute 一次只能验证一件事,所以如果我的模型上有多个验证属性,它将无法正常工作。而且我不确定它是否可以在客户端工作,我什至没有测试它......
【问题讨论】:
-
我一定错过了什么。你说:“但是在这种情况下我将如何验证 Text?我需要它与模型属性 Text 具有相同的验证”。您需要在视图模型中复制的模型上有哪些验证?
-
我需要在 ViewModel 中使用它才能使用客户端验证...
-
你能把属性同时应用到模型和视图模型吗?还是您要避免的重复?
标签: c# asp.net-mvc validation ef-code-first asp.net-mvc-5