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.
 
Question: 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:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="EnhancedDeleteSupportApp.WebForm1" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head id="Head1" runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <center>  
  10.         <div>  
  11.             <asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow" ItemType="EnhancedDeleteSupportApp.Employee"  
  12.                 BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None"  
  13.                 AutoGenerateColumns="false" SelectMethod="GetData" UpdateMethod="UpdateData"  
  14.                 AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" DeleteMethod="DeleteData">  
  15.                 <AlternatingRowStyle BackColor="PaleGoldenrod"></AlternatingRowStyle>  
  16.                 <FooterStyle BackColor="Tan"></FooterStyle>  
  17.                 <HeaderStyle BackColor="Tan" Font-Bold="True"></HeaderStyle>  
  18.                 <PagerStyle HorizontalAlign="Center" BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue">  
  19.                 </PagerStyle>  
  20.                 <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite"></SelectedRowStyle>  
  21.                 <SortedAscendingCellStyle BackColor="#FAFAE7"></SortedAscendingCellStyle>  
  22.                 <SortedAscendingHeaderStyle BackColor="#DAC09E"></SortedAscendingHeaderStyle>  
  23.                 <SortedDescendingCellStyle BackColor="#E1DB9C"></SortedDescendingCellStyle>  
  24.                 <SortedDescendingHeaderStyle BackColor="#C2A47B"></SortedDescendingHeaderStyle>  
  25.                 <Columns>  
  26.                     <asp:BoundField DataField="Id" HeaderText="ID" ReadOnly="true" />  
  27.                     <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />  
  28.                     <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />  
  29.                     <asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />  
  30.                 </Columns>  
  31.             </asp:GridView>  
  32.             <br />  
  33.             <asp:ValidationSummary ID="StudentsValidationSummary" runat="server" ShowSummary="true"  
  34.                 DisplayMode="BulletList" Style="color: Red" />  
  35.         </div>  
  36.     </center>  
  37.     </form>  
  38. </body>  
  39. </html> 
Step 4: The complete code of webform1.aspx.cs looks like this:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. namespace EnhancedDeleteSupportApp  
  8. {  
  9.     public partial class WebForm1 : System.Web.UI.Page  
  10.     {  
  11.         protected void Page_Load(object sender, EventArgs e)  
  12.         {  
  13.         }  
  14.         public IQueryable GetData()  
  15.         {  
  16.             return objEntities.Employee;  
  17.         }  
  18.         public void UpdateData(Employee employee)  
  19.         {  
  20.             if (ModelState.IsValid)  
  21.             {  
  22.                 objEntities.Entry(employee).State = System.Data.EntityState.Modified;  
  23.                 objEntities.SaveChanges();  
  24.             }  
  25.         }  
  26.         public void DeleteData(int id)  
  27.         {  
  28.             Employee obj_Employee = objEntities.Employee.Find(id);  
  29.             objEntities.Employee.Remove(obj_Employee);  
  30.             objEntities.SaveChanges();  
  31.         }  
  32.         #region Instance VariablesCompanyEntities objEntities = new CompanyEntities();#endregion  
  33.     }  

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):
  1. //------------------------------------------------------------------------------  
  2. // <auto-generated>  
  3. // This code was generated from a template.  
  4. //  
  5. // Manual changes to this file may cause unexpected behavior in your application.  
  6. // Manual changes to this file will be overwritten if the code is regenerated.  
  7. // </auto-generated>  
  8. //------------------------------------------------------------------------------namespace EnhancedDeleteSupportApp  
  9.    
  10. using System;  
  11. using System.Collections.Generic;  
  12. using System.ComponentModel.DataAnnotations;  
  13. public partial class Employee  
  14. {  
  15.     [Key]public int Id  
  16.     {  
  17.         get;  
  18.         set;  
  19.     }  
  20.     [Required(ErrorMessage="FirstName is required")]  
  21.     [StringLength(10, ErrorMessage="Cannot be more than 10 characters")]  
  22.     public string FirstName  
  23.     {  
  24.         get;  
  25.         set;  
  26.     }  
  27.     [Required(ErrorMessage = "LastName is required")]  
  28.     [StringLength(10, ErrorMessage="Cannot be more than 10 characters")]  
  29.     public string LastName  
  30.     {  
  31.         get;  
  32.         set;  
  33.     }  
  34.     [Required(ErrorMessage = "Age is required")]  
  35.     [Range(12, 65, ErrorMessage="Age must be between 12 and 65")]  
  36.     public Nullable<int>  
  37.         Age  
  38.     {  
  39.         get;  
  40.         set;  
  41.     }  
  42. }
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


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