Asp.net mvc validation

In ASP.NET MVC you can place your validation code in a lot of places: Creating a custom ValidationAttribute, placing the validation in the Model Binder, placing it in controller or placing it in the Model. The first and second choice has a limitation and that is you have no access to DataContext or repository and you can not pass the records in DB. This Data – which is not accessible in binder or a validator class – is essential for some sort of validation e.g. checking the uniqueness of a field. Placing validation code in the controller is not also good because its reusability is zero! Just think of a change in technology or needing validation in another place. The best place to put validation logic is the Model class where it really belongs to. Just put your codes in a method and then call it in your controller, or if you want a Json Validator write a remote attribute to call a controller method which the controller calls your validation method. Passing records in DB is also possible because in your controller you have access to the repository. The only thing that matters is return type of a validation method which I think the best one is List<KeyValuePair<string,string>> although you can work with any return type that you like. In controller you can easily report validation errors by Foreaching the list and Add errors to the ModelState:

           List<KeyValuePair<string,string>> errors=model.validate();

            if (errors != null && errors.Any())

            {

                errors.ForEach(error=> ModelState.AddModelError(error.Key, error.Value));

            }

 

 

Read 913 times Last modified on Sunday, 23 August 2015 20:28
Rate this item
0
(0 votes)
About Author
Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Advanced Programming Concepts
News Letter

Subscribe our Email News Letter to get Instant Update at anytime