Introduction to Validate Multiple Data Model Properties Using ASP.Net 4.5

Introduction

Note: Before reading this article, go through my first article.

Today we'll learn about the data annotation validators operations inside the GridView. I've already described the Model State Validation in my previous article. We've already done the Model state validation and applying normal validation in the previous article.

In the same context, the data annotation is applied to the model and is inherently applied to only one data model property at a single time. Say, if you have applied the "StringLength" or "Required" attributes, only one property will validate. But in some cases multiple data model properties are also required, in that context here I am developing the same scenario in which there are two techniques that are used to solve the problem.

Validation using the ModelSate

In this section, we'll use the ModelState dictionary to access the properties defined in the model. You can check the values and then flag errors if it is necessary.

Now in this technique we'll modify the DataGridView_UpdateItem() method with the following code:

  1. public void DataGridView_UpdateItem(int ID)  
  2. {  
  3.     ModelStateValidation.Cricketer item = CricketerDbContext.Cricketers.Find(ID);  
  4.     //Load the item here, e.g. item = MyDataLayer.Find(id);  
  5.     if (item == null)  
  6.     {  
  7.         // The item wasn't found  
  8.         ModelState.AddModelError("", String.Format("Item with id {0} was not found", ID));  
  9.     }  
  10.     else  
  11.     {  
  12.         TryUpdateModel(item);  
  13.         if (item.Name.Length < 2 && item.Team.Length < 2)  
  14.         {  
  15.             ModelState.AddModelError("""Name and Team Values are Invalid!!");  
  16.         }  
  17.         if (ModelState.IsValid)  
  18.         {  
  19.             CricketerDbContext.SaveChanges();  
  20.         }  
  21.     }  
  22. } 

You can see that in the code above the Name and Team are the model properties. The ModelState dictionary will display an error message using the AddModelError() method. If you pass the first parameter as an empty then it indicates that the error is a model level error rather than a property level error. If you want to associate the error under consideration to a specific model property then you can specify the name of the property as the first parameter of the AddModelError() method. The second parameter shows the error message that will display (if the condition is true) through the ValidationSummary control.

Validation using IValidatable Interface

We need to implement the IValidatable interface in the model class. It contains the Validate() method that returns the collection of ValidationResult objects. In here, the Cricketer is a Entity Framework designed class so it is the best way to implement this with the Cricketer partial class.

So, modify it as shown below:

  1. using System.Collections;  
  2. using System.ComponentModel.DataAnnotations;  
  3. namespace ModelStateValidation  
  4. {  
  5.     [MetadataType(typeof(CricketerMetaData))]  
  6.     public partial class Cricketer : IValidatableObject  
  7.     {  
  8.         public IEnumerable Validate(ValidationContext context)  
  9.         {  
  10.             List errors = new List();  
  11.             if (Name.Length < 2 && Team.Length < 2)  
  12.             {  
  13.                 ValidationResult result = new ValidationResult("Values of Name and Team are Invalid!!");  
  14.                 errors.Add(result);  
  15.             }  
  16.             return errors;  
  17.         }  
  18.     }  
  19. } 

You can choose the technique to apply to the application. The ModelSate technique puts the validation code in the web form since the ModelState is a property of the Page class.

Run Application

So that's done for the technique and you can run the application.

Step 1: Run the application and click the Edit button with which you can update the data as in the following:

Edting the Data in GridView

Step 2: Enter only one value in both textboxes and click on Update as in the following:

Updating Database from GridView

You can see the following error message in the ValidationSummary control:

Model State Error through Validation Summary

Summary

This article described the various techniques to apply the multiple model state validator inside the GridView using ASP.NET 4.5. Thanks for reading and Happy Coding!!


Similar Articles