Data Annotations For Web Forms in .NET 4.5

Introduction

Today, in this article let's play around with one of the interesting and most useful concepts in .NET 4.5.

What are data annotations in web forms?

In simple terms "It provides enhanced light-weighted validations with data annotation attributes in web forms".

Step 1. Create a new "ASP.Net Web Forms Application", as in.

New-project-in-asp.net.jpg

Step 2. Create an Entity Data Model Framework and set it up with an appropriate database.

Step 3. The complete code of webform1.aspx looks like this.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="EnhancedDeleteSupportApp.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <center>
        <div>
            <asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow" ItemType="EnhancedDeleteSupportApp.Employee"
                BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None"
                AutoGenerateColumns="false" SelectMethod="GetData" UpdateMethod="UpdateData"
                AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" DeleteMethod="DeleteData">
                <AlternatingRowStyle BackColor="PaleGoldenrod"></AlternatingRowStyle>
                <FooterStyle BackColor="Tan"></FooterStyle>
                <HeaderStyle BackColor="Tan" Font-Bold="True"></HeaderStyle>
                <PagerStyle HorizontalAlign="Center" BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue">
                </PagerStyle>
                <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite"></SelectedRowStyle>
                <SortedAscendingCellStyle BackColor="#FAFAE7"></SortedAscendingCellStyle>
                <SortedAscendingHeaderStyle BackColor="#DAC09E"></SortedAscendingHeaderStyle>
                <SortedDescendingCellStyle BackColor="#E1DB9C"></SortedDescendingCellStyle>
                <SortedDescendingHeaderStyle BackColor="#C2A47B"></SortedDescendingHeaderStyle>
                <Columns>
                    <asp:BoundField DataField="Id" HeaderText="ID" ReadOnly="true" />
                    <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
                    <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
                    <asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
                </Columns>
            </asp:GridView>
            <br />
            <asp:ValidationSummary ID="StudentsValidationSummary" runat="server" ShowSummary="true"
                DisplayMode="BulletList" Style="color: Red" />
        </div>
    </center>
    </form>
</body>
</html>

Step 4. The complete code of webform1.aspx.cs looks like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace EnhancedDeleteSupportApp
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public IQueryable GetData()
        {
            return objEntities.Employee;
        }

        public void UpdateData(Employee employee)
        {
            if (ModelState.IsValid)
            {
                objEntities.Entry(employee).State = System.Data.EntityState.Modified;
                objEntities.SaveChanges();
            }
        }

        public void DeleteData(int id)
        {
            Employee obj_Employee = objEntities.Employee.Find(id);
            objEntities.Employee.Remove(obj_Employee);
            objEntities.SaveChanges();
        }

        #region Instance Variables
        CompanyEntities objEntities = new CompanyEntities();
        #endregion
    }
}

Step 5. The complete code of Employee.cs looks like this (you do not need to create this class manually, as the EF framework will create it for you while setting it up under the model folder).

//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EnhancedDeleteSupportApp
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public partial class Employee
    {
        [Key]
        public int Id
        {
            get;
            set;
        }
        [Required(ErrorMessage = "FirstName is required")]
        [StringLength(10, ErrorMessage = "Cannot be more than 10 characters")]
        public string FirstName
        {
            get;
            set;
        }
        [Required(ErrorMessage = "LastName is required")]
        [StringLength(10, ErrorMessage = "Cannot be more than 10 characters")]
        public string LastName
        {
            get;
            set;
        }
        [Required(ErrorMessage = "Age is required")]
        [Range(12, 65, ErrorMessage = "Age must be between 12 and 65")]
        public Nullable<int>
            Age
        {
            get;
            set;
        }
    }
}

Step 6. The output of the application looks like this.

Output-of-the-application-in-asp.net.jpg

Step 7. The data annotation validation output of the application looks like this.

data-annotation-validation-Output-in-asp.net.jpg

Step 8. The age field data annotation validation output of the application looks like this.

Age-with-data-annotation-validation-Output-in-asp.net.jpg


Similar Articles
MVC Corporation
MVC Corporation is consulting and IT services based company.