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

This articles describes the various techniques to apply the multiple model state validator inside the GridView 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:

public void DataGridView_UpdateItem(int ID)

{

    ModelStateValidation.Cricketer item = CricketerDbContext.Cricketers.Find(ID);

    //Load the item here, e.g. item = MyDataLayer.Find(id);

    if (item == null)

    {

        // The item wasn't found

        ModelState.AddModelError(""String.Format("Item with id {0} was not found", ID));

    }

    else

    {

        TryUpdateModel(item);

        if (item.Name.Length < 2 && item.Team.Length < 2)

        {

            ModelState.AddModelError("""Name and Team Values are Invalid!!");

        }

        if (ModelState.IsValid)

        {

            CricketerDbContext.SaveChanges();

        }

    }

 }

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:

using System.Collections;

using System.ComponentModel.DataAnnotations;

 

namespace ModelStateValidation

{

    [MetadataType(typeof(CricketerMetaData))]

    public partial class Cricketer : IValidatableObject

    {

        public IEnumerable Validate(ValidationContext context)

        {            

            List errors = new List();

            if (Name.Length < 2 && Team.Length < 2)

            {

                ValidationResult result = new ValidationResult("Values of Name and Team are Invalid!!");

                errors.Add(result);

            }

            return errors;

        }

    }

}

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 articles 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!!