came across an issue with validation of complex classes in ASP.NET MVC4 using DataAnnotation.
遇到了使用DataAnnotation验证ASP.NET MVC4中的复杂类的问题。
Let's have a following model (simplified)
我们有一个以下模型(简化)
public class Customer
{
[Required]
[StringLength(8, MinimumLength = 3)]
public string UserName { get; set; }
[Required]
[StringLength(8, MinimumLength = 3)]
public string DisplayName { get; set; }
}
public class Order
{
public Customer customer { get; set; }
}
Then I try to validate an instance of this model in my controller:
然后我尝试在我的控制器中验证此模型的实例:
// CREATE A DUMMY INSTANCE OF THE MODEL
Customer cust = new Customer();
cust.UserName = "x";
cust.DisplayName = "x";
Order orderModel = new Order();
orderModel.customer = cust;
// VALIDATE MODEL
TryValidateModel(orderModel); // ModelState.IsValid is TRUE (which is incorrect)
TryValidateModel(cust); // ModelState.IsValid is FALSE (whic is correct}
Validation of orderModel should fail as the cust.UserName has only 1 character, but 3 are required by the Model. Same applies to cust.DisplayName. But when I validate a pure Customer class then it fails as expected.
orderModel的验证应该失败,因为cust.UserName只有1个字符,但Model需要3个字符。同样适用于cust.DisplayName。但是,当我验证纯Customer类时,它会按预期失败。
Any idea what's wrong?
知道什么是错的吗?
thanks
Jiri
1 个解决方案
#1
2
DataAnnotations won't dig into your objects on it's own. You have two choices:
DataAnnotations不会自己挖掘您的对象。你有两个选择:
1--Write a custom validator to check child properties
1 - 编写自定义验证器以检查子属性
2--Create a view model with populated with the simple properties decorated with data annotations
2 - 创建一个视图模型,其中填充了用数据注释装饰的简单属性
#1
2
DataAnnotations won't dig into your objects on it's own. You have two choices:
DataAnnotations不会自己挖掘您的对象。你有两个选择:
1--Write a custom validator to check child properties
1 - 编写自定义验证器以检查子属性
2--Create a view model with populated with the simple properties decorated with data annotations
2 - 创建一个视图模型,其中填充了用数据注释装饰的简单属性