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:

<asp:GridView ID="DataGridView" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" 
ItemType="ModelStateValidation.Cricketer" SelectMethod="DataGridView_GetData" 
UpdateMethod="DataGridView_UpdateItem" Height="234px" Width="469px">

    <Columns>

        <asp:BoundField DataField="ID" HeaderText="Cricketer ID" ReadOnly="true" />

        <asp:TemplateField HeaderText="Name">

            <ItemTemplate>

                <asp:Label ID="LblName" runat="server" Text="<%# Item.Name %>"></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

                <asp:TextBox ID="TxtEditName" runat="server" Text="<%# BindItem.Name %>"></asp:TextBox>

                <asp:RequiredFieldValidator ID="RfvEditName" runat="server" ControlToValidate="TxtEditName"
 ErrorMessage="Name Cannot Be Blank!!"></asp:RequiredFieldValidator>

            </EditItemTemplate>

        </asp:TemplateField>

 

        <asp:TemplateField HeaderText="Team">

            <ItemTemplate>

                <asp:Label ID="LblTeam" runat="server" Text="<%# Item.Team %>"></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

                <asp:TextBox ID="TxtEditTeam" runat="server" Text="<%# BindItem.Team %>"></asp:TextBox>

                <asp:RequiredFieldValidator ID="RfvEditTeam" runat="server" ControlToValidate="TxtEditTeam"
 ErrorMessage="Team Cannot Be Blank!!"></asp:RequiredFieldValidator>

            </EditItemTemplate>

        </asp:TemplateField>

 

        <asp:TemplateField HeaderText="Grade">

            <ItemTemplate>

                <asp:Label ID="LblGrade" runat="server" Text="<%# Item.Grade %>"></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

                <asp:TextBox ID="TxtEditGrade" runat="server" Text="<%# BindItem.Grade %>"></asp:TextBox>

                <asp:Label ID="LblErrorMessage" runat="server" Text=""></asp:Label>

            </EditItemTemplate>

        </asp:TemplateField>

        <asp:CommandField HeaderText="Operations" ButtonType="Button" ShowEditButton="true" />

    </Columns>

</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:

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

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

Cricketer_SiteEntities CricketerDbContext = new Cricketer_SiteEntities();

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

public IQueryable<ModelStateValidation.Cricketer> DataGridView_GetData()

{

    var CricItem = from CricData in CricketerDbContext.Cricketers

                         orderby CricData.ID

                         select CricData;

    return CricItem;

}

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

public void DataGridView_UpdateItem(int ID)

{

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

    if (item == null)

    {

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

    }

    TryUpdateModel(item);

    if (ModelState.IsValid)

    {

        //CricketerDbContext.SaveChanges();

    }

    else

    {

        if (ModelState["Grade"].Errors.Count > 0)

        {

            Label LblError = DataGridView.Rows[DataGridView.EditIndex].
FindControl(
"LblErrorMessage"as Label;

            LblError.Text = "";

            foreach (ModelError Error in ModelState["Grade"].Errors)

            {

                LblError.Text += Error.ErrorMessage + "<br/>";

            }

        }

    }

 }

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:

using System.ComponentModel.DataAnnotations;

 

namespace ModelStateValidation

{

    public class CricketerMetaData

    {

        [Required]

        [StringLength(30, ErrorMessage = "Name can contain only 30 characters")]

        public string Name { getset; }

        [Required]

        [StringLength(15, ErrorMessage = "Team can contain only 15 characters")]

        public string Team { getset; }

        [Required]

        [StringLength(1, ErrorMessage = "Grade can contain only 1 character")]

        public string Grade { getset; }

    }

}

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:

using System.ComponentModel.DataAnnotations;

 

namespace ModelStateValidation

{

    [MetadataType(typeof(CricketerMetaData))]

    public partial class Cricketer

    {

    }

}

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

To download the source code, please click here: ModelStateValidation 

Up Next
    Ebook Download
    View all
    Learn
    View all