Complex class checking in ASP.NET MVC4 fails

There was a problem checking complex classes in ASP.NET MVC4 using DataAnnotation.

Let there be the 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 check an instance of this model in the 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} 

Checking the Model should fail because cust.UserName has only 1 character, but 3 is required for the model. The same applies to cust.DisplayName. But when I check for a clean Client class, it fails as expected.

Any idea what is wrong?

thanks

Jiri

+6
source share
1 answer

DataAnnotations will not dig into your objects yourself. You have two options:

1 - Write a custom validator to check child properties

2 - Create a view model with simple properties filled with data annotations

+2
source

Source: https://habr.com/ru/post/924173/


All Articles