Validating an ASP.NET MVC 2 Model Object

I am trying to check a model object outside the ModelState context in the controller, I currently have a parser that creates model objects from an excel file, and I want to be able to report how many records were added to the databases and how many failed, is there any way to check the model an object on its data annotation outside of model binding?

I am looking for something similar to the rails model method model.valid?or a way to implement this myself.

My current solution simply checks manually if there are several key fields, but this duplicates the requirements between my model class and its metadata, there should be a better way to enable mvc 2's model check validation.

thank

+3
source share
1

Validator, DataAnnotations.

User userEntity = new User();

var validationContext = new ValidationContext(userEntity, null, null);
var validationResults = new List<ValidationResult>();
DataAnnotations.Validator.TryValidateObject(userEntity, validationContext, validationResults, true);

/ , , .

singleton . .

, :

TypeDescriptor.AddProviderTransparent(
    new AssociatedMetadataTypeTypeDescriptionProvider(
        typeof(User),
        typeof(UserMetadata)
    ),
    typeof(User)
);

Validator.TryValidateObject(userEntity, context, results, true);
+2

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


All Articles