Jquery JSON Add,Edit,Update,Delete in Asp .Net

 Hope you have enjoyed my previous articles regarding add, edit, update and delete operations using Listview http://www.codingfusion.com/Post/ListView-Edit-Update-Delete-in-Asp-net-using-Ado and Repeater http://www.codingfusion.com/Post/Repeater-Edit-Update-Delete-in-Asp-net-using-Ado control.

                 In this article we will see how to perform CRUD operations like add, edit, update and delete using JQUERY, JSON, JQUERY-AJAX and entity framework in asp .net. Let's begin with creating database. 

CREATE TABLE [dbo].[Student] (
    [Id]    INT            IDENTITY (1, 1) NOT NULL,
    [Name]  NVARCHAR (100) NULL,
    [Email] NVARCHAR (100) NULL,
    [Age]   NCHAR (10)     NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

Above query will create a new table in your database like this:

Jquery-Json-add-edit-update-delete-using-asp-net

Our database is ready to use. Now we will create a webpage to receive and show data.

 
<%--//=== Here we will show error and confirmation messages.--%>
Name
Email
Age
  <%--//==== We have hide our update button at the initial stage so that only save button is visible at startup.--%> <%--//=== We will use this hidden field to store id of selected record during update operation.--%>
<%--//==== We will show our data in this div--%>

Output will be like this:

Now we have designed our database and page. We are ready now to add JQUERY into our project.

 

Step1: Add this code between head tags of your page.

 

This will add JQUERY in your project using CDN. You can also download latest JQUERY file from internet and add to your project.
Note: If you have added JQUERY using the above code it will only work if you have internet connection.

 

Step2: Create a new Jquery file myScript.Js in your project to write your custom jquery functions.

 

 

Step3: Add reference of your Jquery file to your page. Add these lines between head section of your page.

 

Output: Your head section will look like this:


    
    
    

Lets create our save function in Default.aspx.cs page. To call your method from JQUERY you need to be create method of type [WebMethod]

Step1: Add Name space: using System.Web.Services;

 

Step2: Save Method: 

//using System.Web.Services;
    //==== Method to save data into database.
    [WebMethod]
    public static int saveData(string name, string email, string age)
    {
        try
        {
            int status = 0;
            using (JsonEntities context = new JsonEntities())
            {
                Student obj = new Student();
                obj.Name = name;
                obj.Email = email;
                obj.Age = age;
                context.Students.AddObject(obj);
                context.SaveChanges();
                status = obj.Id;
            }
            return status;
        }
        catch
        {
            return -1;
        }
    }

Step3: Create a save method in your myScript.JS file to call this saveData() method.

//==== Method to save data into database.
function saveData() {

    //==== Call validateData() Method to perform validation. This method will return 0 
    //==== if validation pass else returns number of validations fails.

    var errCount = validateData();
    //==== If validation pass save the data.
    if (errCount == 0) {
        var txtName = $("#txtName").val();
        var txtEmail = $("#txtEmail").val();
        var txtAge = $("#txtAge").val();
        $.ajax({
            type: "POST",
            url: location.pathname + "Default.aspx/saveData",
            data: "{name:'" + txtName + "',email:'" + txtEmail + "',age:'" + txtAge + "'}",
            contentType: "application/json; charset=utf-8",
            datatype: "jsondata",
            async: "true",
            success: function (response) {
                $(".errMsg ul").remove();
                var myObject = eval('(' + response.d + ')');
                if (myObject > 0) {
                    bindData();
                    $(".errMsg").append("
  • Data saved successfully
"); } else { $(".errMsg").append("
  • Opppps something went wrong.
"); } $(".errMsg").show("slow"); clear(); }, error: function (response) { alert(response.status + ' ' + response.statusText); } }); } }

We have used 3 methods in this save method they are:

1)  validateData() method to validate our data.

//==== Method to validate textboxes
function validateData() {

    var txtName = $("#txtName").val();
    var txtEmail = $("#txtEmail").val();
    var txtAge = $("#txtAge").val();
    var errMsg = "";
    var errCount = 0;
    if (txtName.length <= 0) {
        errCount++;
        errMsg += "
  • Please enter Name.
  • "; } if (txtEmail.length <= 0) { errCount++; errMsg += "
  • Please enter Email.
  • "; } if (txtAge.length <= 0) { errCount++; errMsg += "
  • Please enter Age.
  • "; } if (errCount > 0) { $(".errMsg ul").remove() $(".errMsg").append("
      " + errMsg + "
    "); $(".errMsg").slideDown('slow'); } return errCount; }

    2)  bindData() method. This method will create a dynamic html table and inserts into the page to show records we have entered.

    //==== Get data from database, created HTML table and place inside #divData
    function bindData() {
    
        $.ajax({
            type: "POST",
            url: location.pathname + "Default.aspx/getData",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            datatype: "jsondata",
            async: "true",
            success: function (response) {
                var msg = eval('(' + response.d + ')');
                if ($('#tblResult').length != 0) // remove table if it exists
                { $("#tblResult").remove(); }
                var table = "";
                for (var i = 0; i <= (msg.length - 1); i++) {
                    var row = "";
                    row += '';
                    row += '';
                    row += '';
                    row += '';
    
                    row += '';
                    table += row;
                }
                table += '
    NameEmailAgeActions
    ' + msg[i].Name + '' + msg[i].Email + '' + msg[i].Age + '
    '; $('#divData').html(table); $("#divData").slideDown("slow"); }, error: function (response) { alert(response.status + ' ' + response.statusText); } }); }

    bindData() method will call getData() method to get data from the database. So Create this method in your Default.aspx.cs page. You will need to add namespace using System.Web.Script.Serialization;

    //==== Method to fetch data from database.
        //using System.Web.Script.Serialization;
        [WebMethod]
        public static string getData()
        {
            string data = string.Empty;
            try
            {
                using (JsonEntities context = new JsonEntities())
                {
                    var obj = (from r in context.Students select r).ToList();
    
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    data = serializer.Serialize(obj);
                }
                return data;
            }
            catch
            {
                return data;
    
            }
        }
    

    3) clear() Method. This method will clear all the values from textbox controls after data is successfully saved.

    //==== Method to clear input fields
    function clear() {
        $("#txtName").val("");
        $("#txtEmail").val("");
        $("#txtAge").val("");
    
        //=== Hide update button and show save button.
        $("#btnSave").show();
        $("#btnUpdate").hide();
    }
    

    Output: If you have followed all the steps carefully you will see output like this:

    Jquery-Json-add-edit-update-delete-using-asp-net

    Edit operation.

    This method will bind values of selected row into textbox, hides save button, show update button and stores primary key value of selected record in hiddenfield.

     

    Step1: Code behind method in your default.aspx.cs page.

     //==== Method to get values of selected record and bind in input controls for update.
        [WebMethod]
        public static string bindRecordToEdit(int id)
        {
            string data = string.Empty;
            try
            {
    
                using (JsonEntities context = new JsonEntities())
                {
                    var obj = context.Students.FirstOrDefault(r => r.Id == id);
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    data = serializer.Serialize(obj);
                }
                return data;
            }
            catch
            {
                return data;
            }
        }
    

    Step2: Jquery funtion:

    //==== Method to bind values of selected record into input controls for update operation.
    function bindRecordToEdit(id) {
        $.ajax({
            type: "POST",
            url: location.pathname + "Default.aspx/bindRecordToEdit",
            data: "{id:'" + id + "'}",
            contentType: "application/json; charset=utf-8",
            datatype: "jsondata",
            async: "true",
            success: function (response) {
                var msg = eval('(' + response.d + ')');
                $("#txtName").val(msg.Name);
                $("#txtEmail").val(msg.Email);
                $("#txtAge").val(msg.Age);
    
                //=== store id of the selected record in hidden field so that we can use it later during 
                //=== update process.
                $("#hfSelectedRecord").val(id);
    
                //=== Hide save button and show update button.
                $("#btnSave").hide();
                $("#btnUpdate").css("display", "block");
    
    
            },
            error: function (response) {
                alert(response.status + ' ' + response.statusText);
            }
        });
    }
    


    Update operation.

     

    Step1: Code behind method in your default.aspx.cs page.

    //==== Method to update data.
        [WebMethod]
        public static int updateData(string name, string email, string age, int id)
        {
            try
            {
                int status = 0;
                using (JsonEntities context = new JsonEntities())
                {
                    Student obj = context.Students.FirstOrDefault(r => r.Id == id);
                    obj.Name = name;
                    obj.Email = email;
                    obj.Age = age;
                    context.SaveChanges();
                    status = obj.Id;
                }
                return status;
            }
            catch
            {
                return -1;
            }
        }
    

    Step2: Jquery Method.

    //==== Method to update record.
    function updateData() {
    
        //==== Call validateData() Method to perform validation. This method will return 0 
        //==== if validation pass else returns number of validations fails.
    
        var errCount = validateData();
        //==== If validation pass save the data.
        if (errCount == 0) {
            var txtName = $("#txtName").val();
            var txtEmail = $("#txtEmail").val();
            var txtAge = $("#txtAge").val();
            var id = $("#hfSelectedRecord").val();
            $.ajax({
                type: "POST",
                url: location.pathname + "Default.aspx/updateData",
                data: "{name:'" + txtName + "',email:'" + txtEmail + "',age:'" + txtAge + "',id:'" + id + "'}",
                contentType: "application/json; charset=utf-8",
                datatype: "jsondata",
                async: "true",
                success: function (response) {
                    $(".errMsg ul").remove();
                    var myObject = eval('(' + response.d + ')');
                    if (myObject > 0) {
                        bindData();
                        $(".errMsg").append("
    • Data updated successfully
    "); } else { $(".errMsg").append("
    • Opppps something went wrong.
    "); } $(".errMsg").show("slow"); clear(); }, error: function (response) { alert(response.status + ' ' + response.statusText); } }); } }

     

    Delete Operation:

     

    Step1: Code behind method in your default.aspx.cs page.

     //==== Method to Delete a record.
        [WebMethod]
        public static void deleteRecord(int id)
        {
            try
            {
                using (JsonEntities context = new JsonEntities())
                {
                    var obj = context.Students.FirstOrDefault(r => r.Id == id);
                    context.Students.DeleteObject(obj);
                    context.SaveChanges();
                }
            }
            catch
            {
            }
        }
    

    Step2: Jquery Method.

    //==== Method to delete a record
    function deleteRecord(id) {
        //=== Show confirmation alert to user before delete a record.
        var ans = confirm("Are you sure to delete a record?");
        //=== If user pressed Ok then delete the record else do nothing.
        if (ans == true) {
            $.ajax({
                type: "POST",
                url: location.pathname + "Default.aspx/deleteRecord",
                data: "{id:'" + id + "'}",
                contentType: "application/json; charset=utf-8",
                datatype: "jsondata",
                async: "true",
                success: function (response) {
                    //=== rebind data to remove delete record from the table.
                    bindData();
                    $(".errMsg ul").remove();
                    $(".errMsg").append("
    • Record successfully delete.
    "); $(".errMsg").show("slow"); clear(); }, error: function (response) { alert(response.status + ' ' + response.statusText); } }); } }

    To show data on page load create this method in your myScript.Js file:

    //==== To show data when page initially loads.
    $(document).ready(function () {
        bindData();
    });
    

    CSS Used:

     
    

    Final Output:

    Jquery-Json-add-edit-update-delete-using-asp-net

    Jquery-Json-add-edit-update-delete-using-asp-net

    Jquery-Json-add-edit-update-delete-using-asp-net

    Jquery-Json-add-edit-update-delete-using-asp-net

    We are nothing without our users ! You can help us offer even more high quality content. Please share our page !
    Best quality Asp .Net Ajax Control Toolkit tutorials.
    Thanks you for elaborated code. I have just one Doubt What is JsonEntities. I added NameSpace using Newtonsoft.Json.Linq;..But i am not able to find that ..
    10-Feb-2014 From  Rakesh Chaubey
    Hi Rakesh...Thanks for your comment. I have used entity framework to do my save, edit, delete operations and JsonEntities is the object of my entity model. (You can download code and see the structue in App_Code Folder)
    10-Feb-2014 From  Anuj
    I just skimmed this, but here are my comments: 1. Don't bind javascript methods to your elements in your HTML. Do it in your javascript files. 2. Using a validation plugin (eg. jquery validation) will drastically simplify that portion of your code. 3. Use the correct HTTP Methods for each action. Don't always use POST.
    14-Feb-2014 From  Mike Ellis
    Don't you think there is too much code (especially javascript) for such simple operations like CRUD?
    15-Feb-2014 From  Victor
    i am getting 404 error when run this form in my pc.plz give me suggession to fix problems ..
    2-Apr-2014 From  sheik kadar
    Hi Sheik kadar 404 error means there is something wrong with your path.IF you running your application like localhost://appname/Default.aspx try to run like localhost://appname
    6-Apr-2014 From  Anuj
    Hello thanks Very Nice Code. and how to use Paging and Searching in table
    19-May-2014 From  RAM
    Great Job buddy....(Y) keep it up. It's really useful....:D Thumbs up...(Y)
    23-May-2014 From  yasi
    In your example you used something called "using JsonModel;" what's this ?? is this some kind of reference...?? without this "JsonModel" I have some errors. ( ex. using (JsonEntities context = new JsonEntities()) in here.., "JsonEntities" is underlined.) so.., plz help me.
    24-May-2014 From  madu
    Hi madu I have used Entity framework to save, update and delete operations and JsonEntities is part of entity framework. I would like you to study about Entity framework. Or you can simply use ADO.net... just ignore entity framework code.
    25-May-2014 From  Anuj
    Thanks yasi... stay tuned for more articles.
    25-May-2014 From  Anuj
    Hi Ram for paging and searching you need to do custom code or you can use Jqgrid.
    25-May-2014 From  Anuj
    Thanx Ritesh.
    25-May-2014 From  Anuj
    i want create client paging for this table. please help me ...
    9-Jun-2014 From  smf
    thank you for this article. i saw an error when i click "View my complete profile". thanks Line 55: BlogPostCategory catObj = context.BlogPostCategories.FirstOrDefault(r => r.Id == obj.BlogPostCategoryId);
    15-Jun-2014 From  Phan Cong U
    Hi Anuj, Thanks for such a knowledgeable post. My edit button functionality is not working my code is : I am using VS 2008. Please advice.
    17-Jun-2014 From  Akhil Kumar
    how to download App_Code
    22-Jul-2014 From  shanthi
    Thanks for pointing the issue. Solved
    13-Aug-2014 From  Anuj
    rar file is damaged please fix it
    23-Dec-2014 From  Lea
    Thanks for pointing the issue. Fixed.
    18-Feb-2015 From  Anuj

    Give your valuable comments.

    Name
    Email
    Comment
    2 + 4 =
     
    About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2017 CodingFusion