Click here to Skip to main content
Click here to Skip to main content

CRUD Operation in ASP.NET Web Applications Using HTTP Handler and jQuery

By , 20 May 2012
 

Introduction

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. To keep this application simple, I have not covered Validation and any other facets of a well designed application.

Requirements

Earlier, I mentioned that I have used Jquery Ajax API to make Ajax call of HttpHandler so for that, it is required to add reference of the Jquery File. You can get the latest Jquery File From the http://jquery.com or in case you are using VS2010, it will be available by default in Web projects.

Implementation

CRUDOpeartionUsingJQuery/ProductUI.JPG

Then the first step is to create a new ASP.NET WebProjects.

Then create a folder name Script and Add Jquery File and one Commonfunction.js blank JavaScript File.

Add a DataBase

Add SqlServer Database File into the Projects, then create the following Products Table:

CRUDOpeartionUsingJQuery/DBScreenshot.JPG

Now, add Class file named products which is used to perform database operation. Add the following code into that class File.

public class DbProducts
{
    SqlConnection _con = new SqlConnection
    (ConfigurationManager.ConnectionStrings[1].ConnectionString);

    public List<product> GetProductDetails()
    {
        try
        {
            List<product> _lstProducts = new List<product>();
            Product _Product = null;
            if (_con.State != System.Data.ConnectionState.Open)
                _con.Open();
            SqlCommand _cmd = _con.CreateCommand();
            _cmd.CommandText = "Select * From Products";
            SqlDataReader _Reader = _cmd.ExecuteReader();

            while (_Reader.Read())
            {
                _Product = new Product();
                _Product.ProductID = Convert.ToInt32(_Reader["ProductID"]);
                _Product.Name = _Reader["Name"].ToString();
                _Product.Unit = _Reader["Unit"].ToString();
                _Product.Qty = Convert.ToDecimal(_Reader["Qty"]);
                _lstProducts.Add(_Product);

            }
            return _lstProducts;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (_con.State != System.Data.ConnectionState.Closed)
                _con.Close();
        }
    }

    public string InsertProduct(Product _P)
    {
        try
        {
            if (_con.State != System.Data.ConnectionState.Open)
                _con.Open();
            SqlCommand _cmd = _con.CreateCommand();
            _cmd.CommandText = "Insert Into Products(Name,Unit,Qty)Values
                    (@Name,@Unit,@Qty)";
            _cmd.Parameters.Add(new SqlParameter("@Name", _P.Name));
            _cmd.Parameters.Add(new SqlParameter("@Qty", _P.Qty));
            _cmd.Parameters.Add(new SqlParameter("@Unit", _P.Unit));
            if (_cmd.ExecuteNonQuery() > 0)
                return "Record Successfully Saved";
            else
                return "Record not Affected to DataBase";
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (_con.State != System.Data.ConnectionState.Closed)
                _con.Close();
        }
    }

    public string UpdateProduct(Product _P)
    {
        try
        {
            if (_con.State != System.Data.ConnectionState.Open)
                _con.Open();
            SqlCommand _cmd = _con.CreateCommand();
            _cmd.CommandText = "Update Products set Name=@Name,Unit=@Unit,
            Qty=@Qty Where ProductID=@ProductID";
            _cmd.Parameters.Add(new SqlParameter("@Name", _P.Name));
            _cmd.Parameters.Add(new SqlParameter("@Qty", _P.Qty));
            _cmd.Parameters.Add(new SqlParameter("@Unit", _P.Unit));
            _cmd.Parameters.Add(new SqlParameter("@ProductID", _P.ProductID));
            if (_cmd.ExecuteNonQuery() > 0)
                return "Record Successfully Updated";
            else
                return "Record not Affected to DataBase";
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (_con.State != System.Data.ConnectionState.Closed)
                _con.Close();
        }
    }

    public string DeleteProduct(int ProductID)
    {
        try
        {
            if (_con.State != System.Data.ConnectionState.Open)
                _con.Open();
            SqlCommand _cmd = _con.CreateCommand();
            _cmd.CommandText = "Delete From Products Where ProductID=@ProductID";
            _cmd.Parameters.Add(new SqlParameter("@ProductID", ProductID));
            if (_cmd.ExecuteNonQuery() > 0)
                return "Records Successfully Delete";
            else
                return "Records not Affected to DataBase";
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (_con.State != System.Data.ConnectionState.Closed)
                _con.Close();
        }
    }

    public Product GetProductById(int ProductID)
    {
        try
        {
            if (_con.State != System.Data.ConnectionState.Open)
                _con.Open();
            SqlCommand _cmd = _con.CreateCommand();
            _cmd.CommandText = "Select * From Products Where ProductID=@ProductID";
            _cmd.Parameters.Add(new SqlParameter("@ProductID", ProductID));
            SqlDataReader _Reader = _cmd.ExecuteReader();
            Product _Product = null;
            while (_Reader.Read())
            {
                _Product = new Product();
                _Product.ProductID = Convert.ToInt32(_Reader["ProductID"]);
                _Product.Name = _Reader["Name"].ToString();
                _Product.Qty = Convert.ToDecimal(_Reader["Qty"]);
                _Product.Unit = _Reader["Unit"].ToString();
            }
            return _Product;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (_con.State != System.Data.ConnectionState.Closed)
                _con.Close();
        }
    }
}

public class Product
{
    private int _ProductID = 0;

    public int ProductID
    {
        get { return _ProductID; }
        set { _ProductID = value; }
    }

    private string _Name = string.Empty;

    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }

    private string _Unit = string.Empty;

    public string Unit
    {
        get { return _Unit; }
        set { _Unit = value; }
    }

    private decimal _Qty = 0;

    public decimal Qty
    {
        get { return _Qty; }
        set { _Qty = value; }
    }
}

Next, create another class file named JsonResponse which is used to serialize response in a json format. Add the following code into that file.

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

public class JsonResponse
{
    private bool _IsSucess = false;

    public bool IsSucess
    {
        get { return _IsSucess; }
        set { _IsSucess = value; }
    }

    private string _Message = string.Empty;

    public string Message
    {
        get { return _Message; }
        set { _Message = value; }
    }

    private object _ResponseData = null;

    public object ResponseData
    {
        get { return _ResponseData; }
        set { _ResponseData = value; }
    }

    private string _CallBack = string.Empty;

    public string CallBack
    {
        get { return _CallBack; }
        set { _CallBack = value; }
    }
} 

Now add the following HTML into Default.aspx's Body tag for product entry form.

<asp:Label runat="server" ID="lblTime"></asp:Label>
<form id="form1" action="" method="post">
<table cellpadding="2" cellspacing="2" border="1"width="400px">
<tr style="background-color: Gray"> <td colspan="2" align="center">
<b>Product Entry Form</b>
</td>
</tr>
<tr>
   <td>
      Product Name
   </td>
   <td>
      <input type="text" id="txtName"style="width:250px"/>
  </td>
</tr>
<tr>
  <td>
      Unit
  </td>
  <td>
  <input type="text"id="txtUnit"style="width: 250px"/>
  </td>
</tr>
<tr>
  <td>
      Qty
  </td>
  <td>
    <input type="text"id="txtQty"style="width: 250px"/>
   </td>
</tr>
<tr>
  <td colspan="2" align="center">
    <input type="button"id="butSave"value="Save"onclick="SaveProducts()"/>
   </td>
 </tr>
</table>
<br/>
<br/>
   <div id="ListingData">
   </div>
</form>

and add the following script tag into the head tag:

  <script src="Script/jquery-1.2.6.js" type="text/javascript"></script>
  <script src="Script/CommonFunction.js" type="text/javascript"></script>

Next add the handler File named ProductList.ashx which is used to get response when it will call using Jquery. Add the following code into that file:

public class ProductList : IHttpHandler
{
    string MethodName = string.Empty;
    string CallBackMethodName = string.Empty;
    object Parameter = string.Empty;
    DbProducts _DbProducts = new DbProducts();

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/x-javascript";
        MethodName = context.Request.Params["method"];
        Parameter = context.Request.Params["param"];
        CallBackMethodName = context.Request.Params["callbackmethod"];

        switch (MethodName.ToLower())
        {
            case "getproducts":
                context.Response.Write(GetDetails());
                break;
            case "getbyid":
                context.Response.Write(GetById());
                break;
            case "insert":
                context.Response.Write(Insert(context));
                break;
            case "update":
                context.Response.Write(Update(context));
                break;
            case "delete":
                context.Response.Write(Delete());
                break;
        }
    }

    public string GetDetails()
    {
        JsonResponse _response = new JsonResponse();
        System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
                       new System.Web.Script.Serialization.JavaScriptSerializer();
        try
        {
            System.Collections.Generic.List<product> _Products = 
                    _DbProducts.GetProductDetails();
            _response.IsSucess = true;
            _response.Message = string.Empty;
            _response.CallBack = CallBackMethodName;
            _response.ResponseData = _Products;
        }
        catch (Exception ex)
        {
            _response.Message = ex.Message;
            _response.IsSucess = false;
        }
        return jSearializer.Serialize(_response);
    }

    public string GetById()
    {
        JsonResponse _response = new JsonResponse();
        System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
                     new System.Web.Script.Serialization.JavaScriptSerializer();
        try
        {
            Product _Products = _DbProducts.GetProductById(Convert.ToInt32(Parameter));
            _response.IsSucess = true;
            _response.Message = string.Empty;
            _response.CallBack = CallBackMethodName;
            _response.ResponseData = _Products;

        }
        catch (Exception ex)
        {
            _response.Message = ex.Message;
            _response.IsSucess = false;
        }
        return jSearializer.Serialize(_response);
    }

    public string Insert(HttpContext context)
    {
        JsonResponse _response = new JsonResponse();
        System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
                     new System.Web.Script.Serialization.JavaScriptSerializer();
        try
        {
            Product _P = new Product();
            _P.Name = context.Request.Params["name"].ToString();
            _P.Unit = context.Request.Params["unit"].ToString();
            _P.Qty = Convert.ToDecimal(context.Request.Params["Qty"].ToString());
            _response.IsSucess = true;
            _response.CallBack = CallBackMethodName;
            _response.ResponseData = _DbProducts.InsertProduct(_P);
            _response.Message = "SucessFully Saved";
        }
        catch (Exception ex)
        {
            _response.Message = ex.Message;
            _response.IsSucess = false;
        }
        return jSearializer.Serialize(_response);
    }

    public string Update(HttpContext context)
    {
        JsonResponse _response = new JsonResponse();
        System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
                     new System.Web.Script.Serialization.JavaScriptSerializer();
        try
        {
            Product _P = new Product();
            _P.Name = context.Request.Params["name"].ToString();
            _P.Unit = context.Request.Params["unit"].ToString();
            _P.Qty = Convert.ToDecimal(context.Request.Params["Qty"].ToString());
            _P.ProductID = Convert.ToInt32
        (context.Request.Params["ProductID"].ToString());
            _response.IsSucess = true;
            _response.Message = "SucessFully Updated";
            _response.CallBack = CallBackMethodName;
            _response.ResponseData = _DbProducts.UpdateProduct(_P);
        }
        catch (Exception ex)
        {
            _response.Message = ex.Message;
            _response.IsSucess = false;
        }
        return jSearializer.Serialize(_response);
    }

    public string Delete()
    {
        JsonResponse _response = new JsonResponse();
        System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
                     new System.Web.Script.Serialization.JavaScriptSerializer();
        try
        {
            _response.IsSucess = true;
            _response.Message = "Record Successfully Deleted";
            _response.CallBack = CallBackMethodName;
            _response.ResponseData = _DbProducts.DeleteProduct(Convert.ToInt32(Parameter));
        }
        catch (Exception ex)
        {
            _response.Message = ex.Message;
            _response.IsSucess = false;
        }
        return jSearializer.Serialize(_response);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Now, go to Coomonfunction.js, add the following function into that file.

function DoAjaxCall(parameter, datatype, data) {
    jQuery.ajax({
        type: 'POST',
        url: "ProductList.ashx" + parameter,
        data: data,
        dataType: datatype,
        success: function(data, textStatus) {
            try {
                var jsonData = (new Function("return " + data))()
                if (jsonData.IsSucess) {
                    eval(jsonData.CallBack + '(jsonData.ResponseData, jsonData.Message)');
                }
                else {
                    alert(jsonData.Message + jsonData.IsSucess);
                }
            }
            catch (err) {
            }
        },
        error: function() {
            alert("Error");
        }
    });
}

This function is used to call the Http Handler using Ajax. To call this function, we have to just pass parameters like methodname, datatoinsert, callbackfunctionname, datatype and data. If it will perform successfully, then it will go to the success function if there are set is success is true then it will call the callback function and pass the response data into the json format and message, but if any error occurred it will go the error function.

Next, add client side click function of save button:

<input type="button" id="butSave" value="Save" onclick="SaveProducts()" />

and add the following function SaveProducts into the Commonfunction.js which looks like this:

function SaveProducts() {

    var Param = "name=" + document.getElementById("txtName").value + 
    "&unit=" + document.getElementById("txtUnit").value + "&Qty=" + 
    document.getElementById("txtQty").value;
       if (ProductID == 0)
        DoAjaxCall("?method=Insert&callbackmethod=InsertProductSucess", "script", Param);
    else {
        Param += "&ProductID=" + ProductID;
        DoAjaxCall("?method=Update&callbackmethod=UpdateProductSucess", "script", Param);
    }
}

In this function, we have to pass the values to the handler insert data into database, so it will be passed using Querystring. After that, we will check ProductID Global variable which is used to decide current click used to enter the new record into the database or the update record into the database. So if the value of the ProductID is 0, then we have to call the Insert method, otherwise call Update methods.

Now, for the insert, we are passing the parameter as method= Insert and callbackmethod=InserProductSucess and Parameter. Now this function calls DoAjaxCall Global Function which calls the ProductList Handler, so in the Handler in the Process Request method, we will check which method calls using parameter method. It will call that relevant parameter method. That method performs their operation and assigns a value into the JsonResponse Call object and at the end, it will return jsonresponse serialize object from that method.

That Json Response is available into the Sucessfunction and from that, we will just check if that operation performs successfully, then it will call that callback function.

For the call back function, we have to add one function into the commonfunction.js name InsertProductSucess which looks like below:

function InsertProductSucess(data, message) {
    FillListing();
    alert(message);
    ClearValue();
}
function ClearValue() {
    $("#txtName").val("");
    $("#txtUnit").val("");
    $("#txtQty").val("");
}

Here, this method shows that alert message to the user. Now in the same way, add the other function for the other operation in the same way:

$(document).ready(function() { FillListing(); });

function UpdateProductSucess(data, message) {
    FillListing();
    alert(message);
    ProductID = 0;
    ClearValue();
}

function FillListing() {
    DoAjaxCall("?method=getproducts&callbackmethod=FillListingSucess", "script", "");
}

function FillListingSucess(data, message) {
    var str = " <table width="500px" cellspacing="0" cellpadding="2" 
    border="1"><tbody><tr><td align="center" style="background-color: Gray;" 
    colspan="5"><strong>Product Listing Page</strong></td></tr><tr> 
    <td>Product Name</td><td>Unit</td><td>Qty</td><td>Delete</td><td>Edit</td></tr>";

    for (var i = 0; i < data.length; i++) {
        str += "<tr><td>" + data[i].Name + "</td>";
        str += "<td>" + data[i].Unit + "</td>";
        str += "<td>" + data[i].Qty + "</td>";
        str += "<td><a onclick="DeleteProduct(" + data[i].ProductID + ")" 
        href="javascript:void(0)">Delete</a></td>";
        str += "<td><a onclick="EditProduct(" + data[i].ProductID + ")" 
        href="javascript:void(0)">Edit</a></td></tr>";
    }
    str += "</tbody></table>";
    $('#ListingData').html(str);
}

function DeleteProduct(ProductID) {
    DoAjaxCall("?method=delete&callbackmethod=DeleteSucess&param=" + 
        ProductID, "script", "");
}

function DeleteSucess(data, message) {
    FillListing();
    alert(message);
}

function EditProduct(ProductID) {
    DoAjaxCall("?method=getbyid&callbackmethod=EditSucess&param=" + 
        ProductID, "script", "");
}

function EditSucess(data, message) {
    ProductID = data.ProductID;
    $("#txtName").val(data.Name);
    $("#txtUnit").val(data.Unit);
    $("#txtQty").val(data.Qty);
}

Now try to add one Product using Default.aspx. It will add product. You will find that page will not postback and lbltime will not show the updated time or you can also check into Firebug.

FireBug.JPG - Click to enlarge image

Conclusion

The example given above is very basic. You can use any concept for the database operation like Linq, Entity Framework, etc. The example source code is included with this article, you are free to modify it according to your requirement.

History

  • 15th November, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jigar Bagadai
Software Developer
India India
Member
I have been working as a Software Engineer on Microsoft .NET Technology.I have developed several web/desktop application build on .NET technology .My point of interest is Web Development,Desktop Development,Ajax,Json,Jquey,XML etc.I have completed Master of Computer Application in May-2011.I'm not happy unless I'm learning something new.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralGood articlememberNainil21 Apr '13 - 16:43 
Very well written article.
Questiondisconnected architecturememberMohammed Nisar26 Jan '13 - 2:01 
is this possible with disconnected architecture.. if yes how. ?
GeneralMy vote of 5memberSavalia Manoj M28 Dec '12 - 17:06 
Excellent Work...!!
GeneralMy vote of 5memberPhat (Phillip) H. VU26 Dec '12 - 15:37 
Great post.
GeneralMy vote of 5memberRenju Vinod18 Dec '12 - 0:19 
Nice
GeneralMy vote of 5memberinkcolorYui17 Dec '12 - 22:13 
Thanks. Code Good
GeneralMy vote of 4membersharath8226 Sep '12 - 18:23 
good work
Generalgreat, express logically,Vote 5memberAlenty30 Jul '12 - 16:51 
This article is well presented.what's more,You express yourself logically.It is perfect if integrated with Jquery EasyUI library.
GeneralMy vote of 5membermanoj kumar choubey7 Jul '12 - 2:08 
Nice
GeneralMy vote of 5memberNaderC29 May '12 - 5:45 
it content new idea for me. it nice
QuestionDoAjaxCall vs ScriptService MethodmemberAnjum.Rizwi21 May '12 - 19:39 
Excellent, Very well written.
 
I have done similar kind of work using Script Service. Using HTTP Handler is another way however I see there is extra work to read the value from context object where in Script Service call Like
 
 
UIHelper.Insert('', '' , '', OnInsertSuccess)
UIHelper.Delete(22, OnDeleteSuccess)
UIHelper.Update(22, '', OnUpdateSuccess)
 
After looking from all angle, I feel script service is better in this context.
 
What do you think? Can you explain any thing extra that I have not thought or any security aspect.
Hope It will help.
 
Thank You,
Anjum Rizwi
 

AnswerRe: DoAjaxCall vs ScriptService MethodmemberJigar Bagadai30 May '12 - 18:46 
Hello Anjum ,
 
I think you may right.but as per my approach, if you use script service of Microsoft it will load all the dependent JavaScript files and size of that web page response need to think twice.
While if we are using jquery, the size of that file less than script service and i also noticed that Microsoft ,also provide intelisense support for jquery from asp.net 4.0.
 
Let me know better than this concern.There may be possible i may wrong.
Questionjquery-1.7.2.js issuememberEric van Rensburg16 May '12 - 20:02 
Hi Jigar
Worked perfect until I needed to move to a new version of jquery. If you replace jquery-1.2.6.js with jquery-1.7.2.js Error alert is thrown. All is good until function ProcessRequest(HttpContext context)in ProductList.ashx.cs returns. It looks like it may be related to content type?
Any idea?
Thanks
Eric
AnswerRe: jquery-1.7.2.js issuememberJigar Bagadai19 May '12 - 23:02 
Hi Eric
 
I have changed code to solve your problem now check new version of code using below link. Let me know if you found any problem.
http://www.codeproject.com/script/Articles/Preview.aspx[^]
GeneralRe: jquery-1.7.2.js issuememberEric van Rensburg20 May '12 - 10:30 
Hi Jigar
Thanks, working perfectly now against jQuery 1.7.2!
Eric
QuestionUse of HandlermemberMember 422822114 Feb '12 - 21:39 
Hi Jigar Bagadai,
 
I am confuse here with the use of handler, can you please expalin me why you use HttpHandler in this code, can we do the same without handler?
 
Thanks.
Harmeet Singh

AnswerRe: Use of HandlermemberHaBiX20 May '12 - 20:53 
You could use a plaint webpage to respond json data, but that's just wrong.. as you don't need any of the Page's functionality (except response.write); you only need to respond data to request. HttpHandler is the way to do it.
 
If you're just looking for other ways to make calls from client/javascript to server, check also ajax & wcf.
QuestionSecurity Issuememberafasyah1 Dec '11 - 18:25 
Better you cover the security issue, since its vulnerable to SQL Injection/XSS/CSRF
GeneralMy vote of 5memberalexkbecker1 Dec '11 - 0:28 
very good work!!!
GeneralRe: My vote of 5memberJigar Bagadai1 Dec '11 - 4:21 
thank you
GeneralMy vote of 5memberSandeep Ramani30 Nov '11 - 22:14 
Excellent Article...
GeneralRe: My vote of 5memberJigar Bagadai1 Dec '11 - 0:10 
thks

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 20 May 2012
Article Copyright 2011 by Jigar Bagadai
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid