Model State Validation in GridView Using ASP.Net 4.5

Introduction

Today we'll learn to apply the General Validation and Model State Validation in the GridView columns. As you know that the WebForms in the ASP.NET 4.5 supports the Model Binding and they can also use the model validation using data annotation validators. Therefore I am describing it here. We can easily display the error message, generated by the data annotations validators in a web form by using the Validation Summary control.

In that context, we'll create the GridView and perform the operations to apply the validation and Model State Validation in the ASP.NET Web Application. Here, I am using Visual Studio 2013 to create the application.

Let's proceed with the following procedure.

Creating ASP.NET Web Application

  • Open the Visual Studio 2013 and click on "New Project" in the Start window
  • Select the ASP.NET Web Application and enter the application name
  • Add a New Web Form to your project

Adding Entity Data Model

Now, in this section we'll add an ADO.NET Entity Data Model in the application using the following procedure.

Step 1: Add an ADO.NET Entity Data Model and select the "Generate from database".

Model Content Selection in Entity Model

Step 2: Create the connection from your database.

Step 3: Select the table from the database as shown below:

Selecting Tables in Entity Data Model

Step 4: Complete the procedure and it'll show you the table design as shown below:

Table in Entity Data Mode

Working with GridView

Step 1: As I mentioned above, in a Web Form we'll add a GridView and put the validation inside it. So, design the Web Form with the following markup:

  1. <asp:GridView ID="DataGridView" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"   
  2. ItemType="ModelStateValidation.Cricketer" SelectMethod="DataGridView_GetData"   
  3. UpdateMethod="DataGridView_UpdateItem" Height="234px" Width="469px">  
  4.     <Columns>  
  5.         <asp:BoundField DataField="ID" HeaderText="Cricketer ID" ReadOnly="true" />  
  6.         <asp:TemplateField HeaderText="Name">  
  7.             <ItemTemplate>  
  8.                 <asp:Label ID="LblName" runat="server" Text="<%# Item.Name %>"></asp:Label>  
  9.             </ItemTemplate>  
  10.             <EditItemTemplate>  
  11.                 <asp:TextBox ID="TxtEditName" runat="server" Text="<%# BindItem.Name %>"></asp:TextBox>  
  12.                 <asp:RequiredFieldValidator ID="RfvEditName" runat="server" ControlToValidate="TxtEditName"  
  13.  ErrorMessage="Name Cannot Be Blank!!"></asp:RequiredFieldValidator>  
  14.             </EditItemTemplate>  
  15.         </asp:TemplateField>  
  16.         <asp:TemplateField HeaderText="Team">  
  17.             <ItemTemplate>  
  18.                 <asp:Label ID="LblTeam" runat="server" Text="<%# Item.Team %>"></asp:Label>  
  19.             </ItemTemplate>  
  20.             <EditItemTemplate>  
  21.                 <asp:TextBox ID="TxtEditTeam" runat="server" Text="<%# BindItem.Team %>"></asp:TextBox>  
  22.                 <asp:RequiredFieldValidator ID="RfvEditTeam" runat="server" ControlToValidate="TxtEditTeam"  
  23.  ErrorMessage="Team Cannot Be Blank!!"></asp:RequiredFieldValidator>  
  24.             </EditItemTemplate>  
  25.         </asp:TemplateField>  
  26.         <asp:TemplateField HeaderText="Grade">  
  27.             <ItemTemplate>  
  28.                 <asp:Label ID="LblGrade" runat="server" Text="<%# Item.Grade %>"></asp:Label>  
  29.             </ItemTemplate>  
  30.             <EditItemTemplate>  
  31.                 <asp:TextBox ID="TxtEditGrade" runat="server" Text="<%# BindItem.Grade %>"></asp:TextBox>  
  32.                 <asp:Label ID="LblErrorMessage" runat="server" Text=""></asp:Label>  
  33.             </EditItemTemplate>  
  34.         </asp:TemplateField>  
  35.         <asp:CommandField HeaderText="Operations" ButtonType="Button" ShowEditButton="true" />  
  36.     </Columns>  
  37. </asp:GridView> 

In the code above, the column contains one Bound Field and two Template Fields. We've bounded the Bound Filed with the Cricketer's ID column. There are two text boxes, two labels and two required field validators defined in the Template Filed.

The Grade field will be validated from the data annotation validators. The label named LblErrorMessage will show the error message (if any). The ItemType property is set to the Cricketer class and the SelectMethod and UpdateMethod are set to their method manually. We'll modify them in a minute.

Step 2: Add the ValidationSummary control after the GridView with the following markup:

  1. <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowModelStateErrors="true" /> 

Step 3: Add the following code before the Page_Load()

  1. Cricketer_SiteEntities CricketerDbContext = new Cricketer_SiteEntities(); 

Step 4: Modify the DataGridView_GetData() with the following code:

  1. public IQueryable<ModelStateValidation.Cricketer> DataGridView_GetData()  
  2. {  
  3.     var CricItem = from CricData in CricketerDbContext.Cricketers  
  4.                          orderby CricData.ID  
  5.                          select CricData;  
  6.     return CricItem;  
  7. } 

Step 5: Modify the DataGridView_UpdateItem() with the following code:

  1. public void DataGridView_UpdateItem(int ID)  
  2. {  
  3.     ModelStateValidation.Cricketer item = CricketerDbContext.Cricketers.Find(ID);  
  4.     if (item == null)  
  5.     {  
  6.          ModelState.AddModelError("", String.Format("Item with id {0} was not found", ID));  
  7.     }  
  8.     TryUpdateModel(item);  
  9.     if (ModelState.IsValid)  
  10.     {  
  11.         //CricketerDbContext.SaveChanges();  
  12.     }  
  13.     else  
  14.     {  
  15.         if (ModelState["Grade"].Errors.Count > 0)  
  16.         {  
  17.             Label LblError = DataGridView.Rows[DataGridView.EditIndex].  
  18. FindControl("LblErrorMessage"as Label;  
  19.             LblError.Text = "";  
  20.             foreach (ModelError Error in ModelState["Grade"].Errors)  
  21.             {  
  22.                 LblError.Text += Error.ErrorMessage + "<br/>";  
  23.             }  
  24.         }  
  25.     }  
  26. } 

In the code above, the parameter you will pass in the method must match the DataKeyNames value of which the id is defined in the GridView. The ModelState.IsValid property is used to determine the model errors. If the IsValid returns false then it accesses the ModelState for the Grade key. The model state validators show the error message (defined in the model), if the Errors.Count is greater then zero.

Adding Class

Step 1: Just add a new class named CricketerMetadata and replace the code with the following:

  1. using System.ComponentModel.DataAnnotations;  
  2. namespace ModelStateValidation  
  3. {  
  4.     public class CricketerMetaData  
  5.     {  
  6.         [Required]  
  7.         [StringLength(30, ErrorMessage = "Name can contain only 30 characters")]  
  8.         public string Name { getset; }  
  9.         [Required]  
  10.         [StringLength(15, ErrorMessage = "Team can contain only 15 characters")]  
  11.         public string Team { getset; }  
  12.         [Required]  
  13.         [StringLength(1, ErrorMessage = "Grade can contain only 1 character")]  
  14.         public string Grade { getset; }  
  15.     }  
  16. } 

In the code above, we've applied data annotation validators for the various properties.

Step 2: The CricketerMetaData class is still not connected with the Cricketer class, so add a partial class named Cricketer with the following code:

  1. using System.ComponentModel.DataAnnotations;  
  2. namespace ModelStateValidation  
  3. {  
  4.     [MetadataType(typeof(CricketerMetaData))]  
  5.     public partial class Cricketer  
  6.     {  
  7.     }  
  8. } 

Run the application

Now, run the application and click on the Edit button to continue.

Required Field Error:

Validation in GridView

You can see that the RequiredFieldValidator displays the Error Message.

Model State Error:

Model State Validation in GridView

You can see the Model State Validation error message is displayed.

Summary

This article describes the validation and model state error validator operation inside the GridView using ASP.NET Web Application. Thanks for reading and Happy Coding!!


Similar Articles