Entity Class
- Entity classes are used to transfer the data within our Application.
- Entity class represents a database table.
- Entity class name is the same as database tables.
- Property names are same as database table column names.
E.g.: Dept Table
DeptNo, Dname, Loc
Class Dept {
Public int DeptNo {get; set ;}
Public string Dname {get; set ;}
Public string Loc {get; set ;}
}
DataContext class
- DataContext class is responsible to perform database operations.
- This class contains the required method to communicate with the database.
- To develop the methods in the class we can use either ADO.Net Entity framework programming.
Note
- We can prepare multiple entity classes depends on the database tables.
- One DataContext class is enough to perform the operation.
Ex:-
Models
Dept.cs
Datacontext.cs
DataContext
GetDepts ()
GetDept (deptno)
Ex:-
Create mvc Application to perform database operation (CRUD) with ADO.Net
1. Create mvc Application and Add HomeController.
2. Add Dept.cs file to model and prepare Dept Class as follows:
File: Model/Dept.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication.Models
{
public class Dept
{
public int DeptNo {get; set ;}
Public string Dname {get; set;}
Public string Loc {get; set;}
}
}
è Add DataContext.cs fill to model and prepare as follow:
File:/Models/DataContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace MvcApplication.Models
{
public class DataContext
{
public List<Dept> GetDepts()
{
string constr = "Server=mithilesh; Database=MVCDB; User Id=sa; Password=12345";
string cmdText = "Select * from Dept";
SqlDataAdapter da = new SqlDataAdapter(cmdText, constr);
DataSet ds = new DataSet();
da.Fill(ds);
List<Dept> deptList = new List<Dept>();
foreach (DataRow item in ds.Tables[0].Rows)
{
Dept obj = new Dept();
obj.DeptNo=int.Parse(item["DeptNo"].ToString());
obj.Dname = item["DName"].ToString();
obj.Loc = item["Loc"].ToString();
deptList.Add(obj);
}
return deptList;
}
public Dept GetDept(int n)
{
string constr = "Server=mithilesh;Database=MVCDB;User Id=sa; Password=12345";
string cmdText = "Select * from Dept where DeptNo=" + n;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(cmdText, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
Dept obj = new Dept();
if(dr.Read()==true)
{
obj.DeptNo=int.Parse(dr["DeptNo"].ToString());
obj.Dname=dr["Dname"].ToString();
obj.Loc=dr["Loc"].ToString();
}
con.Close();
return obj;
}
}
}
Details.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using MvcApplication.Models;
namespace MvcApplication12.Models
{
public class Details
{
public void AddDept(Dept obj)
{
string constr = "Server=mithilesh;Database=MVCDB;User Id=sa; Password=12345";
string cmdText = string.Format("Insert Into Dept Values({0},'{1}','{2}')", obj.DeptNo, obj.Dname, obj.Loc);
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(cmdText, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
public void DeleteDept(int n)
{
string cmdText = string.Format("Delete from Dept where DeptNo={0}", n);
string constr = "Server=mithilesh;Database=MVCDB;User Id=sa; Password=12345";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(cmdText, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
public void EditDept(Dept obj)
{
string cmdText = string.Format("Update Dept Set DName='{0}', Loc='{1}' Where DeptNo={2}", obj.Dname, obj.Loc, obj.DeptNo);
string constr = "Server=mithilesh;Database=MVCDB;User Id=sa; Password=12345";
SqlConnection con=new SqlConnection(constr);
SqlCommand cmd=new SqlCommand(cmdText,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication12.Models;
using MvcApplication12.Controllers;
namespace MvcApplication12.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
Details ds = new Details();
DataContext db = new DataContext();
public ActionResult Index()
{
List<Dept> deptList = db.GetDepts();
return View(deptList);
}
public ActionResult Details(int id)
{
Dept obj = db.GetDept(id);
return View(obj);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Dept obj)
{
ds.AddDept(obj);
return RedirectToAction("Index");
}
public ActionResult Delete(int id)
{
Dept obj = db.GetDept(id);
return View();
}
[HttpPost]
public ActionResult Delete(string id)
{
int n = int.Parse(id);
ds.DeleteDept(n);
return RedirectToAction("Index");
}
public ActionResult Edit(int id)
{
Dept obj = db.GetDept(id);
return View(obj);
}
[HttpPost]
public ActionResult Edit(Dept obj)
{
ds.EditDept(obj);
return RedirectToAction("Index");
}
}
}
View Page:- Index.cshtml
@using MvcApplication.Models
@model IEnumerable<Dept>
<h2>Department Details</h2>
<hr />
<a href="Home/Create">Create New</a>
<br /><br />
<table align="center" width="80%" style="background-color:#0ff;border:double solid maroon;font-weight:bold;color:maroon;padding:5px 8px 4px 10px;border-color:maroon;font-size:25px" border="2">
<tr>
<th width="20%" height="50px">DeptNo</th>
<th width="20%">DName</th>
<th width="20%">Location</th>
<th width="20%">Operation</th>
</tr>
@{
foreach (Dept item in Model)
{
int n = item.DeptNo;
<tr>
<td>@item.DeptNo</td>
<td>@item.Dname</td>
<td>@item.Loc</td>
<td>
<a href="Home/Details/@n">Details</a>
<a href ="Home/Delete/@n">Delete</a>
<a href="Home/Edit/@n">Edit</a>
</td>
</tr>
}
}
</table>
Create.cshtml
<h2>create New Department</h2>
<hr />
@using(Html.BeginForm())
{
@Html.Label("Department Number:")
@Html.TextBox("DeptNo");
<br /><br />
@Html.Label("Department Name:")
@Html.TextBox("DName");
<br /><br />
@Html.Label("Department Location:")
@Html.TextBox("Loc");
<br /><br />
<input type="submit" name="sb1" value="create" />
}
<br />
<a href="/">Back to Index</a>
Details.cshtml
@using MvcApplication12.Models
@model Dept
<h1>Department Details</h1>
<hr />
<span>
Departmen Number:@Model.DeptNo
</span>
<br /><br />
<span>
Department Name:@Model.Dname
</span>
<br />
<br />
<span>
Department Location:@Model.Loc
</span>
<br /><br />
<a href="/">Back to Index</a>
Delete.cshtml
<h2>Delete </h2>
@using(Html.BeginForm())
{
<span align="center"><b style="color:red;font-size:30px">Do want delete?</b></span>
<input type="submit" name="sb1" value="Delete" />
}
<hr />
<a href="/" >back to Index</a>
Edit.cshtml
@using MvcApplication12.Models
@model Dept
<h1>Edit Department</h1>
<hr />
@using(Html.BeginForm())
{
<span>
Departmt Number
@Html.TextBox("DeptNo",Model.DeptNo)
</span>
<br /><br />
<span>
Deparment Name:
@Html.TextBox("DName",Model.Dname)
</span>
<br /><br />
<span>
Department Location:
@Html.TextBox("Loc",Model.Loc)
</span>
<br /><br />
<input type="submit" name="sb1" value="Edit" />
}
<br /><br />
<a href ="/">Back to Index</a>
------------------X--------------------X------------
LINQ Programing in c#
Linq stands for Language Integreted Queries.
In this concept Microsoft integrated sql style of query techniques in .Net programming languages.
LINQ is introduced in 2008 along with .NET 3.5(VS 2008).
LINQ is used to filter the data from any collection in .NET.
We can apply on different data sources likes arrays, List, ArrayList etc.
Note:
dvanced data access technologies like Entity framework uses LINQ to filter database information.
Advantages of LINQ
1. Easy to access the data from any collection.2. Filtering data is more comfortable as same as database queries.
3. Reduce burden on the program for data filtration.
4. Less code to implement.
Steps to Implement
1. Create data source.
2. Prepare LINQ query.
3. Execute the LINQ query.
Library Information
Namespace: System.Linq;
Library: System.core.dll;
Simple C# program
Programs.cs
Write a program to filter only even numbers from the given array by using LINQ.
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Namespace ConsoleApplications
{
Class Program
{
Static void Main(string [] args)
{
//step1:Create data sources
Int[] arr={13,56,25,8,9,14,38,95,15,10};
//step2: prepare LINQ query
var q1=from n in arr where n%2==0 Select n;
//step3: Execute LINQ query
foreach(int item in q1)
{
Console.Write(“ “+item);
}
Console.WriteLine();
Arr[0]=12;
foreach(int item in q1)
{
Console.Write(“ “+item);
}
Console.WriteLine();
Console.ReadLine();
}
}
}
12 56 8 14 38 10
Example:-
Create a vie
1. var q1=from n in arr where n%2==0
1. var q1=from n in arr where n%2==0
2. var q1=from n in arr where n%2==1
3. Var q1=from n in arr where n>=50
Select n;
Select n;
4. Var q1=from n in arr where( n%2==0
5. var q1=from n in arr Orderby n Select n;
w display Employee details by using linq query.
Model/Emp.cs
Namespace mvcApplications.model
{
Public class Emp
{
Public int EmpNo{get; set;}
Public string EmpName{get; set;}
Public string Sal{get; set;}
}
}
Index.cshtml
@using MvcApplication.Models
<h1>Employee Details</h1>
<hr/>
@{ List<Emp> empList=new List<Emp><()
{
New Emp() {EmpNo=1012, Ename=”scott”,sal=25000},
New Emp() {EmpNo=1013, Ename=”mithilesh”,sal=35000},
New Emp() {EmpNo=1014, Ename=”Dhanajee”,sal=45000},
New Emp() {EmpNo=1015, Ename=”Kajal”,sal=27000},
};
var q1=from e1 in empList where e1.Sal>15000
Orderby e1.sal descending Select e1;
foreach(Emp item in q1)
{
<span>@item.EmpNo,@item.Cname,@item.sal</span>
<br/>
Anonymous Types
->Anonymous types are called as unknown classes.
-> In this concept we can directly create an object without any classes.
->Class will prepare by compiler which is not accessible in coding.
->Anonymous type contains set or read-only properties.
->By using “var” we can refer anonymous type objects.
Eg: - var obj1=new {ID=123, name=”scott”};
var obj=new{Id=123, Name=”scott”};
Obj1.Id
Obj1.Name
var obj2=new {message=”Hello”};
obj2.message
var obj3=new {price=12709, quantity=3};
obj3.price
obj3.Quanttity
Note: -
Anonymous types are actually used when we want read only the required properties in LINQ queries.
Eg:-
Var q1=from e1 in emplist
Select new { eq.Ename,e1.sal};
è Anouymous types will be useful to create html controls by using helper methods.
è In order to set client side attributes in html helper method we are using anonymous type concept.
Eg:-
@html.TextBox {“T1”,”Hellow world”, new {maxLength=5, @readonly=”readonly” style=”color: red;”}
For Edit.cshtml
@using(html.TextBox(“DeptNo”, model.DeptNo,new{readonly=”readonly” style=”color:red;”})
Example
//step1 same as previous example
//step2
var q1=from e1 in emplist select new{e1.Ename,e1.Sal};
//step3
foreach(var item in q1)
{
<span> @item.Ename, @item sal</span>
<br/>
}
Q. Write a program to invoke the method by using user defined delegates.
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
namespace conolseApplication
{
//Delegate creation
Public delegate int TestDelegate(int x)
Class Test
{
Public int square(int x)
{
Int result=x*x;
Return result;
}
}
Class program
{
Static void Main(string[] args)
{
Test obj=new Test();
//step2:Delegate object creation
TestDelegate objDelegate=new TestDelegate(obj.squre);
//step3 method calling with delete object
int n=objDelegate(3);
Console.WriteLine(“Result:”+n);
Console.ReadLine();
}
}
Lambda Expression
Q.What is delegate?
-> Delegate concept is introduced in c#1.0.
-> Delegate is called as functional (method) pointer.
-> Delegate can store address of the methods.
->Mostly delegates are used in events concept of GUI Applications.
Delegates object takes method address (reference) as value.
Note:-
1. Delegates can sore only the methods with same arguments return type.
Q. What is anonymous method concept is introduced in C# 2.0.
-> It reduces coding to make use of delegates.
-> It is an in-line method.
->It does not having method name.
-> It is created by using the delegate keyword.
->It does not require method name and return type.
Uses:-
TestDelegate Td=delegate(int x)
{
Return n*n;
};
Q. What is Lambda Expression?
-> Lambda Expression concept is introduced in C# 3.0.
-> It simplifies the implementation of anonymous method usage.
->It will reduce the coding to prepare anonymous method for delegates usages.
->Lambda Expression mostly used in:-
1. Filtering data from collection.
2. Entity framework.
3. Scaffolding Templates
Uses
TestDelegate td=x=>x*x;
Example
//Write a program to invoke the method by using delegates anonymous methods and lambda Expression.
Class program
{
Static void Main(string [] args)
{
Test obj=new Test();
// 1.Reguler Delegates
TestDelegate d1=new TestDelegate (obj.squre);
Int n;
n=d1(5);
Console.WriteLine(“Result:”+n);
//2.Anonymous methods
TestDelegate dz=delegate(int x);
{
Int result =x*x;
Return result;
};
N=dz(5);
Console.WriteLine(“Result:”+n);
//3. Lambda Expressions
TestDelegate dz=(x) =>x*x;
n=dz(5);
Console.ReadLine();
}
}
}
}
}
Scaffolding Templates in MVC
1.Scaffolding templates are used to create view pages for database operations.
2.It generates basic content automatically to create views.
3. These templates include templates for all database operation (CRUD operations).
3. These templates include templates for all database operation (CRUD operations).
Note:
It will generate only basic content, based on that we can do modify as per our requirements.
Advantages of scaffolding templates
->Makes views preparation is easy for database operations.
->It will reduce the coding burden on the programmer.
-> Makes application development faster.
Q.How scaffolding templates works?
-> What are the scaffolding templates available to generate the views.
->Templates:
1. List (Display all items)
2. Create (Insert)
3. Edit (Update)
4. Delete (Delete)
5. Details (Display single item)
6. Empty
Steps to generate views with scaffolding templates
->Right Click on Action method.
-> Add view
->Check “Create a strongly typed”
-> View “check box”.
->Select “model class”
-> Student(mvcApplication.model)
->Select scaffolding templates.
Eg: - List(choose required template)
->Click “Add “button.
Important question
1. What are strongly typed helper methods in mvc?
2. What is a difference between Html.TextBox and Html.TextBoxfor?
Strongly typed helper method
-> Scaffolding templates uses strongly typed HtmlHelper methods to generate views.
Eg:-
html.LabelFor()
Html.TextBoxFor()
Html.EditorFor()
Html.DispalyFor()
Html.DisplayNameFor()
Html.DisplayNameFor()
->All strongly typed helper methods required lambda Expression.
-> Based on the expression it will identity for which column we are generating controls.
-> Based on the expression it will identity for which column we are generating controls.
Eg:
@Html.LabelFor(model=>model, ENAME)
@Html.DispalyFor(model=>model.ENAME)
NOTE:
-> By default primary column fields are not involved in view page preparation.
-> If we want we can customize according to our requirements.
->In “List” operation primary key is used for generating hyperlinks for Edit/Delete/Details.
Create MVC Application to perform CRUD operation on the Emp table by using Entity framework.
Use something templates to generate views
1. Create MVC Application and HomeController.
2. Add “Emp” table to models by using Entity Framework control.
3. Build the project.
4. Prepare the required action method in HomeController as follows.
HomeController
Public class HomeController: Controller
{
TestDBEntity db=new TestdbEntitiess()
Public ActionResult Index()
{
List<EMP> empList=db.Emps.ToList ();
Return view (emplList);
}
Public ActionResult Create()
{
Return View();
}
[HttpPost]
Public ActionResult Create(Emp obj)
{
Db.EMPs.AddObject (obj);
Db.SaveChange();
Return RedirectToAction (“Index”);
}
Public ActionResult Details(int id)
{
Emp obj=db.EMPs.singleorDefault (e1=>e1.EmpNo==id);
return view(obj);
}
Public ActionResult Edit(int id)
{
Emp obj=db.Emps.singleOrDefault(e1=e1.EMPNO=id);
return view();
}
[HttpPost]
Publics ActionResult Edit(EMP newObj)
{
Emp OldObj=db.Emps.SingleOrDefault(e1=>e1.EMPNO==newObj.EMPNO);
OldObj.ENAME=newObj.ENAME;
Oldobj.Job=newObj.JOB;
OldObj SAL=newOBJ.SAL;
OldObj.DEPTNO=newObj.DEPTNO;
Db.SaveChange ();
Return RedirectToAction (“Index”);
}
Public ActionResult Delete(int id)
{
Emp obj=db.Emps.SingleOrDefault(e1=>e.EMPNO==id);
return view();
}
[HttpPost]
Public ActionResult Delete (string id)
{
Int n=int.Parsse(id);
Emp obj=db.EMPs.SingleOrDefult (e1=>e1.EMPNO==n);
Db.EMPs.DeleteObject (obj);
Db.Save.Changes ();
Return RedirectToAction(“Index”);
}
Entity Framework
Q. What is Entity?
-> Entity framework is an ORM tool from Microsoft.
-> It was released in 2009.
-> It is one of the data accesses technologies in .NET.
What is ORM? What is an example of ORM tools?
-->ORM stand object Relation Mapping.
->ORM concept makes our Application development will be easy.
->ORM concept will provide classes that help to perform database operations will easy.
ORM Class:
1. Entity classes
2. DataContext classes
3. ORM Tools: - To implement ORM concept in the technologies we need to use ORM tools.
4. Examples:
Entity Framework.
LINQ to SQL
Hibernate
NHibernate
NOTE:
->Initially Microsoft introduced LINQ to SQL.
->But due to limitations of LINQ to SQL Microsoft introduced another ORM tool called “Entity Framework”.
-> Most of real-time projects are using entity framework.
->Entity framework can be used in any.Net Applications.
Library information
System.Data.Entity.dll
EntityFramwork.dll
Classes and important method
1. TOList():- To get all record as List <T>, Where T is entity classes.
2. SingleOrDefault ():-To get a single record based on given Lambda expression.
3. AddObject-> VS 2010
4. Add()-VS 2012
->It will give entity class object to the database at the time of saving.
5. DeleteObject():-VS 2010
6. Remove():-VS 2012
-> Remove the given object and will execute delete command at the of saving.
7. SaveChanges ():- After performing all changes we need to execute SaveChange () method to update in the database.
Example:-
Write to display employee details by using the Entity framework.
1. Create a new control Application project.
2. Add Entity framework file to your project.
->Go to solution explorer.
-> Right-click on the project name.
->Add->New item.
-> Visual C#
-> Data
->ADO.Net Entity Data Model
File name:-Model.edmx
3. The above step will open a wizard to follow the steps to provide:
->Connection details.
-> Tables details
-> “Generate form database.
-> Connection details
-> Tables details
-> Click the “Finish” button.
4. Build the project to get entity framework related class in the project.
5. Prepare the following code.
Write to display Employee details by using entity Framework.
Using system;
using System.Collections.Generic;
using System.Text;
namespace consoleApplication
using System.Collections.Generic;
using System.Text;
namespace consoleApplication
{
Class program
Class program
{
Static void Main (string [] args)
{
//Details Statement
TestkdbEntities db=new TestdbEntities();
List<Emp> empList=db.Emps.ToList();
List<Emp> empList=db.Emps.ToList();
foreach(Emp item in empList)
{
Console.Write (“, “+item.EmpNo);
Console.Write (“, “+ item.ENAME);
Console.Write (“, “+item.JOB);
Console.WriteLine ();
}
Console.ReadLine ();
}
}
}
}
Note:
-> In the above program TestDbEnties, EMP classes are user defined classes that are auto generated by Entity Framework.
-> In the above program TestDbEnties, EMP classes are user defined classes that are auto generated by Entity Framework.
-> In order to implement database operation using Entity framework, we may use different types of approaches.
->Entity framework supports 3 different approach t implement.
->All these approaches will perform similar take. I.e. database operations but only way of implementation will be different.
1. Database First Approach
2. Model First Approach
3. Code First Approach
Database First Approach
->In this approach we are creating database tables first.
->Based on the database we generate .edmx(Entity Model).
-> Finally it will generate code for the required classes Entity DataContext classes.
Model First Approch
->In the Model First approach, we can create Entities directly on the designer of *.EDMX file.
->Create an Entity with “Entity Framework” controls from Toolbox.
->In this approach entity model preparation manual implementation.
-> Based on the preparation of entity in *.edmx file we can generate:
1. Dat2. Code for Entity classes DataContext classes.
abase Tables
abase Tables
Steps to implement code First Approach
1. Create Entity classes
2. Create a DataContext class.
3. Prepare Connection
String in Web.config
NOTE:
> Note of the connection string should the same as the name of the DataContext class name.
New classes Related Code First
1. DbContext
2. DbSet(T)
Note
namespace: System.Data.Entity;
Note:
These new classes available after Entity Framework 4.1 versions.
Example:
Create MVC Application to perform CRUD operations on student information by using code First Approach.
1. Create MVC Application and HomeController.
2. Add required classes to model folder.
3. filename:EntityClass.cs
EntityClass.cs
Using System.Web;
Using System.Data.Entity;
namespace mvcAppliaction.Models
{
Public class student
{
Public int studentId{get; set;}
Public string sname{get; set;}
Public string course{get; set;}
Public int Duration{get; set;}
}
//step2
Public class studentDataContext:DbContext
{
Public DbSet<student> Students{get; set;}
}
}
->Prepare the required connection string in web.config.
<Connection string>
<add----/>
<add name=”studentDataContext” connection string=”server=mithilesh;
Database=mkDb;User Id=sa;Password=12345; provider Name=”system.Data.SqlClient”/>
</connection string>
Create required action methods in HomeController as follow.
HomeController.cs
Using System mvcApplication.Models;
namespace mvcApplication:Controllers
{
Public class student
{
studentDataContext db=new studentDataContext();
public ActionResult Index()
{
List<student> stList=db.students.ToList();
return View(stList);
}
Public ActionResult create()
{
return view();
}
[HttpPost]
Public ActionResult Create(student obj)
{
Db.Students.Add(obj);
Db.Savechange();
return RedirectToAction(“Index”);
}
Public ActionResult Details(int id)
{
Student obj=db.student.SingleOrDetails(s1=>s1.studentId==id);
return view(obj);
}
}
}
Create view page for above action method by scaffold templates.
NOTE:
Organizing the database and tables by entity framework in code first approach.
Q. How to transfer multiple objects from the controller to view?
Q. What is the “View Model” in mvcAppliaction?
->ViewModel is a technique to transfer multiple objects from the controller to view.
->We need to create a separate class in the “Model” folder to implement.
->We need to create a separate class in the “Model” folder to implement.
->This class may contain combinations of multiple class objects as properties.
->It may be a single object or multiple objects.
->We can transfer multiple objects from the controller to view in two ways.
1. By ViewData.
2. By using the “ViewModle” “ class.
By ViewData
Student obj=new student()
Course obj2=new Course()
ViewData[“s1”]=obj1;
ViewData [“c1”]=obj2;
student s1=(student)ViewData[“b1”];
Course c1=(course)ViewData[“c1”];
ViewModel
->Create a class in models.
Public class testViewModel
->Prepare object for ViewModel class in controller.
Student obj1=new student();
Course obj2=new course();
testviewModel obj=new testViewModel();
obj.s1=obj1;
obj.c1=obj2;
return view(obj);
->View Page
@model testviewModel
Model S1.studentid
------------ - - - - - -
Data Annotation and validation in MVC
Library info
Library:
System.CommponentModel.DataAnnotation.dll
namespace:
System.ComponentModel.DataAnotations
Attributes classes
-> In .Net all attributes classes implement the following rules :
>Inherits from attribute class.
>Inherits from attribute class.
>Class name end with “attribute” word.
-> All validation related attribute in mvc is inherited in MVC are inherits from “validation attributes” class.
Q. What is an attribute in c#?
-> Attribute in c# is a class that is used to provide to additional information to programming item(class, method,properties etc)
-> Base on the attribute, execution engine like CLR,MVC handler etc will take the decisions.
[HttpPost]
[HttpGet]
[NonAction]
Data Annotation Attribute classes
Example
Create an ASP.Net MVC application to perform validations customer data:
->Add “Customer.cs” file to model folder and define the customer class as following:
Customer.cs
using componentModel.DataAnnotation
using System.Web.Mvc(Not required for vs 2012 and 13)
namespace mvcApplication.Model
{
Public class customer
{
[Required]
[Display(Name=”Customer first value)”]
{
Public class customer
{
[Required]
[Display (Name=”customer first name”)]
[(required=”last name should not be empty”)]
Public string firstname{get; set;}
Public string LastName{get; set;}
[Required]
[Range(20,40)]
Public int Age{get; set;}
[Regular Expression (“\\d{6}]
Public string PinCode{get; set;}
[Data Type(DataType.EmailAddress)]
Public string Email{get; set;}
[Compare(“Email”)]
Public string CustomerEmail{getr;set;}
Step2
Add HomeController and define following Action method.
HomeController. Cs
using MVCApplicatio.Model
namespace MVCApplication.Controller
{
Public class HomeController:Controller
{
Public ActionResult Index()
{
return View();
}
Public ActionResult Crate()
{
return view ();
}
[HttpPost]
Public ActionResult Create(Customer obj)
{
If(ModelState.Isvalid==true)
{
Response.Write (“Customer details are registered in database”);
}
return View();
}
Add view pages for above action method.
->Generate view for create by using scaffold template.
->Prepare index view as follows.
Index.cshtml
<h2> Index</h2>
<a href=”/Home/Create”> Create New customer</a>
Note
-> In MVC Application validation will perform at the client-side by default.
->The client validations are implementing the required javascript.
->If JavaScript is disabled then validation will perform server-side by controller class.
->Controller class provides is a special object called the Model State. This Object will content when the validation is failed are passed with is valid property.
Validation Data Using Data Annotation Attributes in ASP.NET MVC
The data entered by the end-user in various form fields must be validated before it is saved in the database. Developers often use validation HTML helpers provided by ASP.NET MVC to perform the input validations. Additionally, we can also use data annotation attributes from the System.ComponentModel.DataAnnotations namespace to perform validations at the model level. Data annotation attributes are attached to the properties of the model class and enforce some validation criteria. They are capable of performing validation on the server-side as well as on the client-side. This article discusses the basics of using these attributes in an ASP.NET MVC application.
Overview of Data Annotation Attributes
Data annotation attributes are a set of attributes residing in the System.ComponentModel.DataAnnotations namespace that allows you to validate the property values of a model class. Once added they can perform validations on the server-side as well as on the client-side. The important data annotation attributes used for data validation are as follows:
- Required: Ensures that a property has been assigned some value.
- Range: Ensures that a property value falls within a minimum and maximum value.
- StringLength: Can be used to check the length of a string property. You can either specify the maximum permissible length or maximum and minimum permissible length.
- EmailAddress: Validates that an email address with a valid email format has been supplied as a property value.
- Url : Validates that a valid URL has been supplied as a property value.
- RegularExpression: Uses a regular expression to ensure that a property value matches the specified pattern.
Now that we have some ideas about data annotation attributes, let's develop a simple ASP.NET MVC application that makes use of these attributes for data validation.
Creating a Model Class
Begin by creating a new ASP.NET MVC project and select the Empty project template. Then add a new SQL Server database named UserDb to the App_Data folder and create a table - UserProfile. The UserProfile table has columns as shown in the following figure:
The UserProfile table
As we can see from the above model class, the UserProfile table consists of eight columns, viz. Id, FirstName, LastName, Email, Bio, Age, BlogUrl and Phone. Once we create the UserProfile table make sure to add an ADO.NET Entity Data Model to the project so that we get the UserProfile entity class as shown above. In this example, we will validate all of the columns except Id, using various data annotation attributes.
Creating Metadata Class
If our model class is a plain .NET class (POCO) then we can directly decorate its properties with data annotation attributes. However, in this case our model class is an Entity Framework class. Since the data model class is automatically created for us by the Visual Studio designer it is not recommended to modify the same class file. The recommended approach is to create a metadata class and decorate its properties with data annotation attributes. Let's see how.
Add a new class in the Models folder and name it UserProfileMetadata. Write the following code in the UserProfileMetadata class.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
using System.ComponentModel.DataAnnotations;
- using System.ComponentModel;
- namespace DataAnnotationDemo.Models
- {
- public class UserProfileMetadata
- {
- [DisplayName("First Name :")]
- [Required]
- [StringLength(50,MinimumLength=3,ErrorMessage="First Name must be between 3 and 50 characters!")]
public string FirstName { get; set; }
- [DisplayName("Last Name :")]
- [Required]
- [StringLength(50, MinimumLength = 3, ErrorMessage = "Last Name must be between 3 and 50 characters!")]
public string LastName { get; set; }
- [DisplayName("Email :")]
- [Required]
- [EmailAddress(ErrorMessage="Invalid Email")]
- public string Email { get; set; }
- [DisplayName("Profile :")]
- [StringLength(500, ErrorMessage = "Bio must be less than 500 characters!")]
- public string Bio { get; set; }
- [DisplayName("Age :")]
- [Required]
- [Range(18,100)]
- public int Age { get; set; }
- [DisplayName("Blog URL :")]
- [Required]
- [Url(ErrorMessage = "Invalid URL!")]
- public string BlogUrl { get; set; }
- [DisplayName("Phone :")]
- [Required]
- [RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}",ErrorMessage="Invalid Phone Number!")]
- public string Phone { get; set; }
- }}
The UserProfileMetadata class contains property definitions for FirstName, LastName, Email, Bio, Age, BlogUrl and Phone. Notice the attributes that are used to decorate these properties. The [DisplayName] attribute is used to specify a friendly name for the property under consideration. This friendly name is used by HTML helpers such as Html.LabelFor() to display the field name on a view. If we don't use the [DisplayName] attribute a property name will be used for display purpose. The [Required] attribute indicates that a property value must be provided. The [StringLength] attribute is used to specify the maximum length and optionally the minimum length for a property value. For example, the [StringLength] attribute used on the FirstName property specifies the maximum length for FirstName to be 50 and MinimumLength to be 3. The ErrorMessage property of the data annotation attribute indicates an error message that will be displayed in case there is any validation error. If we don't specify any ErrorMessage, a default error message is displayed.
The [EmailAddress] attribute validates a property for a valid email address. The [Range] attribute checks whether a property value falls between a minimum and a maximum value. In the above example, the [Range] attribute checks whether the Age is between 18 and 100. The [Url] attribute checks whether a property value is a valid URL. Finally, the [RegularExpression] attribute checks whether a property value matches a pattern as specified by a regular expression. In this example, we validate the Phone property with a regular expression for US phone numbers.
At this stage, the UserProfileMetadata class is just an independent class in our project. It is not yet linked with the UserProfile model class. To attach the metadata defined in the UserProfileMetadata class to the UserProfile class we need to add a partial class to the project and then use the [MetadataType] attribute as shown below:
- [MetadataType(typeof(UserProfileMetadata))]
- public partial class UserProfile
- {
- }
Adding a Controller and Views
Now, add a new controller in the Controllers folder and name it HomeController. Add the following code to the HomeController class.
- namespace DataAnnotationDemo.Controllers
- {
- public class HomeController : Controller
- {
public ActionResult Index()
- {
- return View();
- }
[HttpPost]
- public ActionResult Index(UserProfile profile)
- {
- if (ModelState.IsValid)
- {
UserDbEntities db = new UserDbEntities();
- db.UserProfiles.Add(profile);
- db.SaveChanges();
- return View("Success");
- }
else
- {
- return View(profile);
- }
- }
}
- }
The HomeController class contains two versions of the Index() action method. The first version is used when we make a GET request and the other is used when the form is submitted by the end-user. The second Index() method accepts UserProfile as a parameter. Inside, it checks whether all the properties of the model class (UserProfile) contain valid values. This checking is done using the ModelState.IsValid property. The IsValid property returns false if any of the properties contain invalid values. If so, the Index view is rendered bypassing the profile object as the model data. If IsValid returns true, the data is added to the UserProfile table and a success view is rendered.
The following figure shows how the Index view looks like. It also shows validation error messages displayed for various invalid values.
The Index View
A part of the HTML markup of the Index view is as follows:
- <%using(Html.BeginForm("Index","Home",FormMethod.Post)){ %>
- <table cellpadding="10" border="1">
- <tr>
- <td>
- <%= Html.LabelFor(m=>m.FirstName) %>
- </td>
- <td>
- <%= Html.TextBoxFor(m=>m.FirstName) %>
- <%= Html.ValidationMessageFor(m=>m.FirstName) %>
- </td>
- </tr>
- ...
- ...
- ...
- <tr>
- <td colspan="2">
- <%= Html.ValidationSummary() %>
- </td>
- </tr>
- </table>
- <%}%>
As we can see the Index view makes use of HTML helpers such as LabelFor(), TextBoxFor() and ValidationMessageFor(). At the end of the form there is also a validation summary.
Add a CSS file to the project and create two CSS classes as shown below:
- .field-validation-error {
- font-weight:bold;
- color:red;
- }
- .validation-summary-errors {
- font-weight:bold;
- color:red;
- }
The ValidationMessageFor() and ValidationSummary() helpers use these classes by default while rendering the validation error messages.
Now, run the project and test various validation rules.
Adding Client Validation Capabilities
We will find that currently the validations are performed on the server-side. That means, when we submit a form containing validation errors, the control goes to the server only to return with error messages. To avoid this round trip we can add client-side capabilities to the Index view. To do so, add the following markup in the <head> section of the Index view.
- <head runat="server">
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- <link href="../../StyleSheet.css" rel="stylesheet" />
- <script src='<%= Url.Content("~/scripts/jquery-1.7.1.js") %>'></script>
- <script src='<%= Url.Content("~/scripts/jquery.validate.js") %>'></script>
- <script src='<%= Url.Content("~/scripts/jquery.validate.unobtrusive.js") %>'></script>
- </head>
The above markup uses the Url.Content() helper to get URLs of three script files, viz. jquery-1.7.1.js, jquery.validate.js and jquery.validate.unobtrusive.js. These files are required for performing client side validation. Now, open web.config and ensure that the following keys exist in the <appSettings> section:
- <appSettings> ...
- <add key="ClientValidationEnabled" value="true" />
- <add key="UnobtrusiveJavaScriptEnabled" value="true" />
- </appSettings>
The ClientValidationEnabled and UnobtrusiveJavaScriptEnabled keys are set to true.
Run the project again. This time validations will happen on the client-side without any server round trip
No comments:
Post a Comment