In this article I am going to explain how can we achieve simple crud operation (create, read, update and delete) using Jquery and Http handler in asp.net without using asp.net heavy controls on web page.
This article will demonstrate step-by-step, how to create a basic application of CRUD (Create, Read, Update, Delete) Operations using HttpHandler in ASP.Net and JQuery Ajax API. We will also see how can we use jquery.ui modal dialog and datepicker and for database we will use entity framework code first approach that will automatically generate database and required tables according to our DbContext class.
Let’s follow the steps in order to create an application:
1) Open Microsoft Visual Studio
2) Select New Project
3) Select Web from the Installed Templates
4) Select ASP.NET Empty Web Application
5) Enter the project name CRUDOperationUsingASHX in the Name textbox
6) Click OK.
7) Add a web form in an application (EmployeeForm.aspx)
8) Now add some required libraries through Package Manager Console.
a) Go to Tools
b) Select Library Package Manager
c) Select Package Manager Console
To Install JQuery type the following command:
install-package jquery
To install jquery.ui type the flowing command:
Install-package jquery.ui.combined
To install entity framework type the following command:
Install-package entityframework
To install Json package type the following command:
Install-package Newtonsoft.Json
9) Add a generic hander in a project (EmployeeDetails.ashx)
10) Add a class JsonResponse in a project:
namespace CRUDOperationUsingASHX
{
publicclassJsonResponse
{
publicbool IsSuccess { get; set; }
publicstring Message { get; set; }
publicobject Data { get; set; }
publicstring CallBack { get; set; }
}
}
11) Add another class Employee in a project:
using System;
namespace CRUDOperationUsingASHX
{
publicclassEmployee
{
publicint Id { get; set; }
publicstring FirstName { get; set; }
publicstring LastName { get; set; }
publicDateTime Dob { get; set; }
publicstring Country { get; set; }
publicstring Address { get; set; }
}
}
12) Add one more class in a project EmployeeDbContext:
using System.Data.Entity;
namespace CRUDOperationUsingASHX
{
publicclassEmployeeDbContext: DbContext
{
publicDbSet<Employee> Employees { get; set; }
}
}
13) You also have to configure your web.config file for the implementation of this project. Add the connectionStrings element under configuration tag:
<connectionStrings>
<addname="EmployeeDbContext"connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=EmployeeDb;Integrated Security=true;"providerName="System.Data.SqlClient" />
</connectionStrings>
14) Add a java script file for an application (app.js)
After adding above libraries and project files the solution explorer should something like below:
Now we will cover coding part in our application.
15) Enter the html and css in EmployeeForm.aspx page given below:
<%@PageLanguage="C#" AutoEventWireup="true"CodeBehind="EmployeeForm.aspx.cs"Inherits="CRUDOperationUsingASHX.EmployeeForm"%>
<!DOCTYPEhtml>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title></title>
<linkhref="Content/themes/base/minified/jquery-ui.min.css" rel="stylesheet"/>
<scriptsrc="Scripts/jquery-2.0.3.js"></script>
<scriptsrc="Scripts/jquery-ui-1.10.3.js"></script>
<scriptsrc="Scripts/app.js"></script>
<styletype="text/css">
body
{
font-family: Georgia, Verdana;
font-size: .9em;
}
#div-employee-formdiv {
padding-bottom:10px;
}
#div-employee-formdivspan{
display:inline-block;
width:130px;
}
.grid {
margin-top:10px;
border: 1pxsolid black;
display:table;
}
.grid.header {
display:table-row;
border: 1pxsolid black;
}
.grid.headerspan {
font-weight:bold;
display:table-cell;
padding:10px;
border-bottom:1pxsolid black;
border-right:1pxsolid black;
}
.grid.content {
display:table-cell;
padding:10px;
}
</style>
</head>
<body>
<formid="form1"runat="server">
<div>
<ahref="#" class="openDialog"title="New Employee Form">Create New</a>
</div>
<divid="div-employee-list" class="grid">
</div>
<divid="div-employee-form" style="display: none;">
<div>
<span>First Name:</span>
<inputtype="text" id="txtFirstName"/>
</div>
<div>
<span>Last Name:</span>
<inputtype="text" id="txtLastName"/>
</div>
<div>
<span>Date of Birth:</span>
<inputtype="text" id="txtDob"/>
</div>
<div>
<span>Country:</span>
<selectid="cmbCountry">
<optionvalue="">Select Country</option>
<optionvalue="India">India</option>
<optionvalue="Newzeland">Newzeland</option>
</select>
</div>
<div>
<spanstyle="vertical-align:top;">Address:</span>
<textareacols="20" rows="2"id="txtAddress"></textarea>
</div>
</div>
<divid="div-confirm-dialog" style="display:none">
<span>Are you sure want to delete this record?</span>
</div>
</form>
</body>
</html>
16) EmployeeDetails.ashx contains the following code to insert, update, delete the data into the database and read the data from the database:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace CRUDOperationUsingASHX
{
publicclassEmployeeDetails : IHttpHandler
{
string methodname = string.Empty;
string callbackmethodname = string.Empty;
string parameter = string.Empty;
EmployeeDbContext dbEmployee = newEmployeeDbContext();
publicvoid ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
methodname = context.Request.Params["method"];
parameter = context.Request.Params["param"];
callbackmethodname = context.Request.Params["callbackmethod"];
switch (methodname.ToLower())
{
case"getemployees":
context.Response.Write(GetEmployees());
break;
case"getbyid":
context.Response.Write(GetById(int.Parse(context.Request.Params["Id"])));
break;
case"insert":
context.Response.Write(Insert(context));
break;
case"update":
context.Response.Write(Update(context));
break;
case"delete":
context.Response.Write(Delete(int.Parse(context.Request.Params["Id"])));
break;
}
}
publicstring Insert(HttpContext context)
{
JsonResponse response = newJsonResponse();
try
{
Employee emp = newEmployee
{
FirstName = context.Request.Params["FirstName"],
LastName = context.Request.Params["LastName"],
Dob = Convert.ToDateTime(context.Request.Params["Dob"]),
Country = context.Request.Params["Country"],
Address = context.Request.Params["Address"]
};
dbEmployee.Employees.Add(emp);
dbEmployee.SaveChanges();
response.IsSuccess = true;
response.Data = emp;
response.Message = "Employee inserted successfully!";
response.CallBack = callbackmethodname;
}
catch (Exception ex)
{
response.IsSuccess = false;
response.Message = ex.Message;
}
returnJsonConvert.SerializeObject(response);
}
publicstring Update(HttpContext context)
{
JsonResponse response = newJsonResponse();
try
{
int id = int.Parse(context.Request.Params["Id"]);
Employee emp = dbEmployee.Employees.FirstOrDefault(m => m.Id == id);
emp.FirstName = context.Request.Params["FirstName"];
emp.LastName = context.Request.Params["LastName"];
emp.Dob = Convert.ToDateTime(context.Request.Params["Dob"]);
emp.Country = context.Request.Params["Country"];
emp.Address = context.Request.Params["Address"];
dbEmployee.SaveChanges();
response.IsSuccess = true;
response.Data = emp;
response.Message = "Employee updated successfully!";
response.CallBack = callbackmethodname;
}
catch (Exception ex)
{
response.IsSuccess = false;
response.Message = ex.Message;
}
returnJsonConvert.SerializeObject(response);
}
publicstring Delete(int id)
{
JsonResponse response = newJsonResponse();
try
{
Employee emp = dbEmployee.Employees.FirstOrDefault(m => m.Id == id);
if (emp != null)
{
dbEmployee.Employees.Remove(emp);
dbEmployee.SaveChanges();
response.IsSuccess = true;
response.CallBack = callbackmethodname;
response.Data = "Employee Deleted successfully!";
response.Message = "Employee Deleted successfully!";
}
else
{
response.IsSuccess = false;
response.Message = "Employee not exist!";
}
}
catch (Exception ex)
{
response.IsSuccess = false;
response.Message = ex.Message;
}
returnJsonConvert.SerializeObject(response);
}
publicstring GetEmployees()
{
JsonResponse response = newJsonResponse();
try
{
IEnumerable<Employee> employees = dbEmployee.Employees.ToList();
response.IsSuccess = true;
response.CallBack = callbackmethodname;
response.Data = employees;
}
catch (Exception ex)
{
response.Message = ex.Message;
response.IsSuccess = false;
}
returnJsonConvert.SerializeObject(response);
}
publicstring GetById(int id)
{
JsonResponse response = newJsonResponse();
try
{
Employee emp = dbEmployee.Employees.FirstOrDefault(m => m.Id == id);
response.IsSuccess = true;
response.CallBack = callbackmethodname;
response.Data = emp;
}
catch (Exception ex)
{
response.IsSuccess = false;
response.Message = ex.Message;
}
returnJsonConvert.SerializeObject(response);
}
publicbool IsReusable
{
get
{
returnfalse;
}
}
}
}
17) Client side script file (app.js) contains the following code in order to open modal dialog, creating datepicker, making ajax request and updating the ui (User Interface) dynamically by using jquery.
var employeeId = 0;
$(function () {
$.ajaxSetup({ cache: false });
$("a").button();
$("#txtDob").datepicker();
$(document).on('click', '.openDialog', function (event) {
event.preventDefault(); //use this or return false
var $title = $(this).attr("title");
var data = $(this).attr("data-val");
$("#div-employee-form").dialog({
title: $title,
autoOpen: false,
resizable: false,
height: 340,
width: 380,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
buttons: {
"Save": function () {
saveEmployee();
},
"Cancel": function () {
$(this).dialog('close');
}
},
open: function (ev, ui) {
if (data) {
employeeId = data;
getEmployeeById(employeeId);
}
},
close: function (ev, ui) {
}
});
$("#div-employee-form").dialog('open');
returnfalse;
});
$(document).on("click", ".confirmDialog", function (event) {
event.preventDefault();
var data = $(this).attr("data-val");
$("#div-confirm-dialog").dialog({
title: 'Delete Employee',
autoOpen: false,
resizable: false,
height: 170,
width: 300,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
buttons: {
"Done": function () {
employeeId = data;
deleteEmployee(employeeId);
},
"Cancel": function () {
$(this).dialog('close');
}
},
});
$("#div-confirm-dialog").dialog('open');
returnfalse;
});
getEmployeeList();
});
function makeAjaxCall(parameter) {
$.ajax({
type: 'POST',
url: "EmployeeDetails.ashx",
data: parameter,
dataType: 'json',
success: function (response) {
if (response.IsSuccess) {
eval(response.CallBack + '(response.Data, response.Message)');
}
else {
}
},
error: function () {
}
})
}
function getEmployeeList() {
makeAjaxCall({ method: "getemployees", callbackmethod: "getEmployeeListOnSuccess" })
}
function getEmployeeListOnSuccess(data) {
var html = "<div class='header'><span>First Name</span><span>Last Name</span><span>DOB</span><span>Country</span><span>Address</span></div>";
$.each(data, function (i, val) {
html += createRow(val);
});
$("#div-employee-list").html(html);
}
function getEmployeeById(id) {
makeAjaxCall({ method: "getbyid", callbackmethod: "editEmployeeSuccess", Id: id });
}
function insertEmployeeSuccess(data, message) {
alert(message);
$("#div-employee-form").dialog('close');
$("#div-employee-list").append(createRow(data));
}
function editEmployeeSuccess(data) {
setValues(data);
}
function updateEmployeeSuccess(data, message) {
var divToUpdate = $(".grid div[id=" + employeeId + "]");
var rowHtml = createRow(data);
var newDiv = $(rowHtml).filter("div[id=" + employeeId + "]");
$(divToUpdate).html($(newDiv).html());
alert(message);
employeeId = 0;
$("#div-employee-form").dialog('close');
}
function deleteEmployeeSuccess(message) {
var divToUpdate = $(".grid div[id=" + employeeId + "]");
$(divToUpdate).remove();
alert(message);
employeeId = 0;
$("#div-confirm-dialog").dialog('close');
}
function saveEmployee() {
var firstNameValue = $("#txtFirstName").val();
var lastNameValue = $("#txtLastName").val();
var dobValue = $("#txtDob").val();
var countryValue = $("#cmbCountry").val();
var addressValue = $("#txtAddress").val();
if (employeeId == 0)
makeAjaxCall({ method: "insert", callbackmethod: "insertEmployeeSuccess", FirstName: firstNameValue, LastName: lastNameValue, Dob: dobValue, Country: countryValue, Address: addressValue });
else
makeAjaxCall({ method: "update", callbackmethod: "updateEmployeeSuccess", Id: employeeId, FirstName: firstNameValue, LastName: lastNameValue, Dob: dobValue, Country: countryValue, Address: addressValue });
}
function deleteEmployee(id) {
makeAjaxCall({ method: "delete", callbackmethod: "deleteEmployeeSuccess", Id: id });
}
function createRow(objEmployee) {
var htmlRow = "";
var dateValue = new Date(objEmployee.Dob);
var dateValueAfterFormat = dateValue.getFullYear() + "-" + (dateValue.getMonth() + 1) + "-" + dateValue.getDate();
htmlRow += "<div style='display:table-row' id=\"" + objEmployee.Id + "\">";
htmlRow += "<span class='content'>" + objEmployee.FirstName + "</span>";
htmlRow += "<span class='content'>" + objEmployee.LastName + "</span>";
htmlRow += "<span class='content'>" + dateValueAfterFormat + "</span>";
htmlRow += "<span class='content'>" + objEmployee.Country + "</span>";
htmlRow += "<span class='content'>" + objEmployee.Address + "</span>";
htmlRow += "<a class='content openDialog' href='#' data-val=\"" + objEmployee.Id + "\">Edit</a>";
htmlRow += "<a class='content confirmDialog' href='#' data-val=\"" + objEmployee.Id + "\">Delete</a>";
htmlRow += "</div>";
return htmlRow;
}
function setValues(objEmployee) {
$("#txtFirstName").val(objEmployee.FirstName);
$("#txtLastName").val(objEmployee.LastName);
//12/03/2013
var dateValue = new Date(objEmployee.Dob);
var dateValueAfterFormat = (dateValue.getMonth() + 1) + "/" + dateValue.getDate() + "/" + dateValue.getFullYear();
$("#txtDob").val(dateValueAfterFormat);
$("#cmbCountry").val(objEmployee.Country);
$("#txtAddress").val(objEmployee.Address);
}
After the doing and understanding the above major stuff, let’s build and run an application, the ouput should be something like below figure:
In order to add or create a new employee, click on Create New button, it will show you a employee entry form in modal dialog.
You can fill the necessary details of employees provided in the form and save it into the database by using Save button.
After adding or updating the data will be reflected in the grid format in main application form i.e. EmployeeForm.aspx
You can also delete the employee record by using delete hyperlink in the employee record in the grid.
In the same way you can also edit the employee information.
Thanks for reading this article. I think this will help you a lot.
Please provide you valuable comments and suggestions.
Daoose Nox
19-Jul-2016