Friday, 4 April 2014

How to create simple Gridview using JQuery and Ajax?


Description:

Welcome to Jqueryjohn.com.

In this article, I will explain how to create simple JQuery Gridview using Ajax.

One of my friends asked me to add, edit and delete a record to html table like Gridview on client side without postback. I have chosen JQuery for this.

Using JQuery Gridview, user can able to Add, Edit and Delete a record without refreshing the page.

For displaying the records like Gridview, i am getting the records as Json object from the server using Ajax and binding with the html table.

Ajax used to connect with the server side without reloading the page.

If the user wants to add new row, it opens new dialog window with the input fields. Just add the values and save it. Added data will append with the html table without refreshing the page.

If the user wants to update a particular record, click the update image on the row. It opens dialog window, modify the values and save it.

While calling AJAX method through JQuery, the method should be static and it should be web method.

Advantage of having JQuery Gridview is, there is no postback for every operation. It increases performance also.

Example program:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="jquery-1.10.2.js" type="text/javascript"></script>
    <script src="jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
    <link href="jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        $(document).ready(function () {
            LoadPage();
            $("#PopupContent").dialog({
                title: "PopUp Title",
                autoOpen: false,
                height: 200,
                width: 300,
                modal: true
            });
            $("#btnSave").click(function () {
                DoOperation();
                return false;
            });
            $("#btnCancel").click(function () {
                DefaultMode();
                return false;
            });
        });
    </script>
    <script type="text/javascript">
        function DefaultMode() {
            $("#PopupContent").dialog("close");
        }
        function AddUpdateMode() {
            $("#PopupContent").dialog("open");
        }
        function LoadPage() {
            $.ajax({
                type: "POST",
                url: "AJAXTABLE.aspx/GetRecords",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function successcall(response) {
                    $("#tblGrid").empty();
                    $("#tblGrid").prepend("<tr>" + "<th>" + "" + " </th>" + "<th>" + "" + " </th>" + "<th>" + "" + "</th>" + "<th>" + "" + "</th>" + "<th>" + "<iimg src='add.png' onclick=\"AddMode() \"/>" + " </th>" + "</tr>");
                    $("#tblGrid").append("<tr>" + "<th>" + "ID" + " </th>" + "<th>" + "Name" + " </th>" + "<th>" + "Age" + "</th>" + "<th>" + "Update" + " </th>" + "<th>" + "Delete" + "</th>" + "</tr>");
                    for (var i = 0; i < response.d.length; i++) {
                        $("#tblGrid").append("<tr>" + "<td>" + response.d[i].Id + " </td>" + "<td>" + response.d[i].Name + " </td>" + "<td>" + response.d[i].Age + "</td>" + "<td>" + "<iimg src='update.png' onclick=\"UpdateMode(" + response.d[i].Id + ",'" + response.d[i].Name + "'," + response.d[i].Age + ")\" />" + "</td>" + "<td>" + "<iimg src='delete.png' onclick=\"DeleteMode(" + response.d[i].Id + ",'" + response.d[i].Name + "'," + response.d[i].Age + ")\" />" + "</td>" + "</tr>"); //replace iimg to img
                    }
                },
                error: function () {
                    alert("Error");
                }
            });
            return false;
        }
        function DoOperation() {
            var hidvalue = $("#hdnMode").val();
            if (hidvalue == "Add") {
                var pID = "0";
                var name = $('#txtName').val();
                var age = $('#txtAge').val();
            }
            else if (hidvalue == "Update") {
                var name = $('#txtName').val();
                var age = $('#txtAge').val();
                var pID = $('#hdnPkid').val();
            }
            else if (hidvalue == "Delete") {
                var name = "";
                var age = "";
                var pID = $('#hdnPkid').val();
            }
            $.ajax({
                type: "POST",
                url: "AJAXTABLE.aspx/DoOperation",
                data: "{'Id':'" + pID + "','Name': '" + name + "','Age':'" + age + "','HidMode':'" + hidvalue + "' }",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d == true) {
                        $('#hdnPkid').val("");
                        DefaultMode();
                        LoadPage();
                    }
                    else {
                        alert("Failure!!!");
                    }
                }
            });
            return false;
        }
        function AddMode() {
            AddUpdateMode();
            $('#txtName').val("");
            $('#txtAge').val("");
            $("#hdnMode").val("Add");
        }
        function UpdateMode(Id, Name, Age) {
            AddUpdateMode();
            $("#hdnMode").val("Update");
            $('#txtName').val(Name);
            $('#txtAge').val(Age);
            $('#hdnPkid').val(Id);
        }
        function DeleteMode(Id, Name, Age) {
            $("#hdnMode").val("Delete");
            $('#hdnPkid').val(Id);
            if (confirm("Do you want to delete this record")) {
                DoOperation();
            }
        }
    </script>
    <style type="text/css">
        #ParentContent table
        {
            width: 300px;
            border: 1px;
        }
        #ParentContent table td
        {
            width: 60px;
            color: Red;
            text-align: center;
        }
        #ParentContent table th
        {
            width: 60px;
            color: Green;
            text-align: center;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="ParentContent">
            <table id="tblGrid" border="1px">
            </table>
        </div>
        <div id="PopupContent">
            <table>
                <tr>
                    <td>
                        <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>
                    </td>
                    <td style="width: 50%">
                        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblAge" runat="server" Text="Age"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnSave" runat="server" Text="Save" />
                    </td>
                    <td>
                        <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
                        <input id="hdnMode" type="hidden" name="hdnMode" runat="server" />
                        <input id="hdnPkid" type="hidden" name="hdnPkid" runat="server" />
                    </td>
                </tr>
            </table>
        </div>
    </div>
    </form>
</body>
</html>

Code behind:

namespace JqueryJohn_sample
{
    public partial class AJAXTABLE : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [System.Web.Services.WebMethod]
        public static clsTSample[] GetRecords()
        {
            List<clsTSample> obj = new List<clsTSample>();
            DataTable dt = new DataTable();
            SqlConnection con = new SqlConnection("Data Source=---;Initial Catalog=dbname;User ID=---;Password=---;");
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from TSample", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            con.Close();
            clsTSample ClsObj = null;
            foreach (DataRow tblerow in dt.Rows)
            {
                ClsObj = new clsTSample();
                ClsObj.Id = Convert.ToInt32(tblerow["Id"]);
                ClsObj.Name = tblerow["Name"].ToString();
                ClsObj.Age = Convert.ToInt32(tblerow["Age"]);
                obj.Add(ClsObj);
            }
            return obj.ToArray();
        }

        [System.Web.Services.WebMethod]
        public static bool DoOperation(string Id, string Name, string Age, string HidMode)
        {
            try
            {
                SqlConnection con = new SqlConnection("Data Source=----;Initial Catalog=dbname;User ID=--;Password=---;");
                con.Open();
                if (HidMode == "Add")
                {
                    SqlCommand cmd = new SqlCommand("insert into TSample (Name, Age) values('" + Name + "','" + Age + "')", con);
                    cmd.ExecuteNonQuery();
                }
                else if (HidMode == "Update")
                {
                    int SId = Convert.ToInt32(Id);
                    SqlCommand cmd = new SqlCommand("update TSample set Name='" + Name + "', Age='" + Age + "' where id='" + SId + "'", con);
                    cmd.ExecuteNonQuery();
                }
                else if (HidMode == "Delete")
                {
                    int SId = Convert.ToInt32(Id);
                    SqlCommand cmd = new SqlCommand("delete from TSample where id='" + SId + "'", con);
                    cmd.ExecuteNonQuery();
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }


    }
    public class clsTSample
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

    }

}

The above code tested successfully and it works fine.


Create gridview dynamically using jquery,  Add, edit and delete data on gridview using jquery, create simple gridview using jquery, bind data to table or gridview using jquery,  perform operation on gridview without postback using jquery. 

1 comment: