Click here to Skip to main content
15,885,914 members
Articles / Web Development / ASP.NET
Tip/Trick

Bind Gridview using AJAX

Rate me:
Please Sign up or sign in to vote.
4.29/5 (12 votes)
20 May 2014CPOL2 min read 107.3K   18   4
Bind gridview using Ajax post method and jQuery

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.

Reference: What 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.

JavaScript
  $.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:

SQL
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
 <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("<tr><th>Username</th>  
                        <th>Firstname</th>  <th>Lastname</th>  
                        <th>EmailID</th></tr>");
                        for (var i = 0; i < data.d.length; i++) {

                            $("#grdDemo").append("<tr><td>" + 
                            data.d[i].Firstname + "</td> <td>" + 
                            data.d[i].Lastname + "</td> <td>" + 
                            data.d[i].Username + "</td> <td>" + 
                            data.d[i].EmailID + "</td></tr>");
                        }
                    }
                },
                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
C#
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<DetailsClass> Detail = new List<DetailsClass>();

           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

License

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


Written By
Team Leader eInfochips
India India



Nirav Prabtani




I am a team lead, Database Architect and Designer /Technical Architect/Analyst,
Programmer in Microsoft .NET Technologies & Microsoft SQL Server with more than
4.5 years of hands on experience.



I love to code....!!! Smile | :)



My recent past includes my work with the education domain as a technical business
requirement analyst, database architect & designer and analyst programmer; just
love my involvement with the world of knowledge, learning and education and I think
I know quite well what I want to do in life & in my career. What do I like? Well,
ideation, brainstorming, coming up with newer and more creative ways of doing things;
each time with an enhanced efficiency. An item in my day's agenda always has a task
to look at what I did yesterday & focus on how I can do it better today




Contact Me

Nirav Prabtani


Mobile : +91 738 308 2188



Email : niravjprabtani@gmail.com


My Blog:
Nirav Prabtani



Comments and Discussions

 
QuestionIs there a mistake in the index.aspx code? Pin
Member 137458467-May-18 10:23
Member 137458467-May-18 10:23 
GeneralMy vote of 3 Pin
Sunasara Imdadhusen20-May-14 22:25
professionalSunasara Imdadhusen20-May-14 22:25 
GeneralRe: My vote of 3 Pin
Nirav Prabtani20-May-14 23:06
professionalNirav Prabtani20-May-14 23:06 
GeneralRe: My vote of 3 Pin
Nirav Prabtani27-Nov-14 1:53
professionalNirav Prabtani27-Nov-14 1:53 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.