Contact Me

Nirav Prabtani

Mobile : +91 738 308 2188

Email : niravjprabtani@gmail.com

Nirav Prabtani

Wednesday 28 May 2014

Bind Gridview using AJAX

Introduction

In this tip, I am going to write about binding of a gridview using Ajax post method.
Now a days, technology has become much faster so Ajax is very useful in our web development instead of classic code behind style of C#.
I have used Ajax POST method to bind gridview. First of all, let's start from AJAX.

What is AJAX ?

AJAX = Asynchronous JavaScript and XML.
In short; AJAX is about loading data in the background and displaying it on the webpage, without reloading the whole page.
Examples of applications using AJAX: Gmail, Google Maps, Youtube, and Facebook tabs.
You can learn more about AJAX from AJAX tutorial.
ReferenceWhat is Ajax?

Background

I bind gridview using Ajax POST method and jQuery.
In Ajax post method, there is a building block for retrieving data from database using web method.
Let's see the structure of Ajax POST method.
             $.ajax({
                type: "POST",    //Method name GET or POST
                url: "PAGENAME/FUNCTION NAME",
                contentType: "application/json;charset=utf-8",
                data: {},        //Parameters to pass in to function at web method
                dataType: "json",
                success: function (data) {
   
                   //On success
                },
                error: function (result) { //On Error
           });  
As seen in above snippet, there is a structure of a Ajax POST method where:
  1. type is for Ajax method type whether it is GET or POST
  2. url specifies the page url and function name of a web method at code behind
  3. data is used to pass parameters to web method function
  4. success used is a function which will be executed on a complete success callback of a web method request, from where you can manipulate returned data from web method
  5. error is executed when any error occurs during Ajax requests and response
Let us see code snippets for Gridview binding using AJAX.

Using the Code

First of all, create database having name DemoDatabase.
Then run that SQL script for create table DemoTable and insert data into table:
USE [DemoDatabase]
GO
create table DemoTable
  (
      id int identity(1,1),
      Username varchar(50),
      Firstname varchar(50),
      Lastname varchar(50),
      EmailID nvarchar(50)  
  )
SET IDENTITY_INSERT [dbo].[DemoTable] ON 

GO
INSERT [dbo].[DemoTable] ([id], [Username], [Firstname], [Lastname], 
[EmailID]) VALUES (1, N'nirav9', N'Nirav', N'Prabtani', N'niravjprabtani@gmail.com')
GO
INSERT [dbo].[DemoTable] ([id], [Username], [Firstname], [Lastname], 
[EmailID]) VALUES (2, N'Raj', N'Rajan', N'Mrug', N'raj@hotmail.com')
GO
INSERT [dbo].[DemoTable] ([id], [Username], [Firstname], [Lastname], 
[EmailID]) VALUES (3, N'Dhamo', N'Dharmendra', N'Pansara', N'dhams@live.com')
GO
INSERT [dbo].[DemoTable] ([id], [Username], [Firstname], [Lastname], 
[EmailID]) VALUES (4, N'Rajesh', N'Rajesh', N'Saradhara', N'rajesh@gmail.com')
GO
SET IDENTITY_INSERT [dbo].[DemoTable] OFF
GO 
Suppose there is one page having name Index.aspx.

Index.aspx

1) Index.aspx
 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js" 
    type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            BindGridView();

        });

        function BindGridView() {

            $.ajax({
                type: "POST",
                url: "Index.aspx/GetData",
                contentType: "application/json;charset=utf-8",
                data: {},
                dataType: "json",
                success: function (data) {

                    $("#grdDemo").empty();

                    if (data.d.length > 0) {
                        $("#grdDemo").append("
Username  
                        Firstname  Lastname  
                        EmailID
");
                        for (var i = 0; i < data.d.length; i++) {

                            $("#grdDemo").append("
"
 + 
                            data.d[i].Firstname + "
" + data.d[i].Lastname + " " + data.d[i].Username + " " + data.d[i].EmailID + ""); } } }, error: function (result) { //alert("Error login"); } }); } </script> </head> <body> <form id="frm1" runat="server"> <asp:GridView ID="grdDemo" runat="server"> </asp:GridView> </form> </body> </html>
2) Index.aspx.cs
 protected void Page_Load(object sender, EventArgs e)
        {
            BindDummyItem(); //Bind dummy datatable to grid view to bind data in it.
        }
        public void BindDummyItem()
        {
            DataTable dtGetData = new DataTable();
            dtGetData.Columns.Add("Username");
            dtGetData.Columns.Add("Firstname");
            dtGetData.Columns.Add("Lastname");
            dtGetData.Columns.Add("EmailID");
            dtGetData.Rows.Add();

            grdDemo.DataSource = dtGetData;
            grdDemo.DataBind();
        }

        [WebMethod] 
        public static DetailsClass[] GetData() //GetData function
        {
            List Detail = new List();

            string SelectString = "Select Username,Firstname,Lastname,EmailID from DemoTable";
            SqlConnection cn = new SqlConnection("Data Source=servername;
            Initial Catalog=DemoDatabase;User ID=User;Password=*****");
            SqlCommand cmd = new SqlCommand(SelectString,cn);
            cn.Open();

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dtGetData = new DataTable();

            da.Fill(dtGetData);

            foreach(DataRow dtRow in dtGetData.Rows)
            {
                DetailsClass DataObj = new DetailsClass();
                DataObj.Username = dtRow["Username"].ToString();
                DataObj.Firstname = dtRow["Firstname"].ToString();
                DataObj.Lastname = dtRow["Lastname"].ToString();
                DataObj.EmailID = dtRow["EmailID"].ToString();

                Detail.Add(DataObj);            
            }

            return Detail.ToArray();
        }
        public class DetailsClass //Class for binding data
        {
            public string Username { get; set; }
            public string Firstname { get; set; }
            public string Lastname { get; set; }
            public string EmailID { get; set; }
        
        }

[Note]

Here, I have used classic method for retrieving data from database for simplicity and for ease of understanding, you can do it by three tier, n-tier and any other secure framework as you want.
In this manner, you can bind and design gridview using Ajax POST method and jquery.

Points of Interest

I have used this functionality many times and in a different way, you can do it on DIV also and bind it like that, it is very fast.
You can apply stylesheet also in success function to give an appearance to element.
You can build this gridview expandable or draggable and many other functionalities with jQuery.
Here is one article on Expandable Table like a Gridview using C#.

History

  • Initial post: 20 May 2014

No comments :

Post a Comment