jQuery pages load faster
this is the first reason why jQuery's popularity continues to grow with .NET
developers. Here our requirement is to bind GridView faster than traditional
one. There are many ways to bind ASP.NET GridView using jQuery. This article
will show you the simplest way to do that. If you do not have any idea about
jQuery AJAX call, I recommend you to read the following articles where I have
explained the way to make AJAX jQuery call in ASP.NET.
Using
jQuery AJAX to call ASP.NET page method
Save
data to database without postback using jQuery ajax in ASP.NET
Using
jQuery ajax to call ASP.NET page method to execute store procedure
Let's
starts from database side. I have used Northwind database to bind Product
details to GridView.
Please follow the link to download
Northwind database.
http://northwinddatabase.codeplex.com/releases/view/71634
Add
GridView control in aspx page
First
thing what you have to do in aspx page is just add GridView control. That’s it,
you don't need to use any bound field. Because we are going to bind GridView in
client side with jQuery.
<asp:GridView ID="gvProduct" runat="server" CssClass="Grid">
</asp:GridView>
Bind Empty data on server side
It's
required to bind empty data to our GridView, then only you can able to populate
GridView using jQuery. For that I have created Datatable with five fields given
below.
public void BindDummyData()
{
DataTable
dt = new DataTable();
dt.Columns.Add("ProductID");
dt.Columns.Add("ProductName");
dt.Columns.Add("QuantityPerUnit");
dt.Columns.Add("UnitPrice");
dt.Columns.Add("UnitsInStock");
dt.Rows.Add();
gvProduct.DataSource = dt;
gvProduct.DataBind();
}
Create WebMethod
Here we
have to create WebMethod declared as static and return type as an array. You
don't need to have any doubt, ASP.NET Ajax page method always to be static
because they are entirely stateless and they don't create any instance of your
page's class. It's quite interesting to read Dave Ward's articles, please
follow the link if you want to understand more about this,
Why
do ASP.NET AJAX page methods have to be static?
[WebMethod]
public static ProductDetails[]
GetData()
{
List<ProductDetails> MyData = new List<ProductDetails>();
string
cmdstr = "SELECT TOP 8 ProductID, ProductName,
QuantityPerUnit, UnitPrice, UnitsInStock FROM Products";
using (SqlConnection conn = new
SqlConnection
(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
{
SqlCommand
cmd = new SqlCommand(cmdstr,
conn);
conn.Open();
SqlDataAdapter
da = new SqlDataAdapter(cmd);
DataTable
dt = new DataTable();
da.Fill(dt);
foreach
(DataRow DR in
dt.Rows)
{
ProductDetails
objProduct = new ProductDetails();
objProduct.ProductID = DR["ProductID"].ToString();
objProduct.ProductName = DR["ProductName"].ToString();
objProduct.QuantityPerUnit = DR["QuantityPerUnit"].ToString();
objProduct.UnitPrice = DR["UnitPrice"].ToString();
objProduct.UnitsInStock = DR["UnitsInStock"].ToString();
MyData.Add(objProduct);
}
return
MyData.ToArray();
}
}
public class ProductDetails
{
public string ProductID { get;
set; }
public string ProductName { get;
set; }
public string QuantityPerUnit { get;
set; }
public string UnitPrice { get;
set; }
public string UnitsInStock { get;
set; }
}
Add
jQuery Library:
We have to add jQuery library. You can
download jQuery library here, or you can use
following jQuery CDN.
<script src ="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript">
</script>
jQuery ajax method:
When
user request our page, it will consume the data by calling WebMethod which we
have written on server side or code behind. WebMethod returns data as an array
and it will be append as a table format like <tr><th><td>
HTML tags along with data.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
contentType: "application/json;charset=utf-8",
data: {},
dataType: "json",
success: function (data) {
$("#gvProduct").empty();
if
(data.d.length > 0) {
$("#gvProduct").append("<tr><th>Product ID</th>
<th>Product Name</th><th>Quantity Per
Unit</th><th>Unit Price</th><th>Units In
Stock</th></tr>");
for (var i = 0; i <
data.d.length; i++) {
$("#gvProduct").append("<tr><td>" +
data.d[i].ProductID + "</td> <td>" +
data.d[i].ProductName +
"</td> <td>" +
data.d[i].QuantityPerUnit + "</td>
<td>" +
data.d[i].UnitPrice + "</td> <td>" +
data.d[i].UnitsInStock
+ "</td></tr>");
}
}
},
error: function
(result) {
//Handling
error
}
});
});
</script>
Add Style
<style type="text/css">
.Grid {
background-color:
#fff;
margin:
5px 0 10px 0;
border:
solid 1px #525252;
border-collapse:
collapse;
font-family:
Calibri;
color:
#474747;
}
.Grid
td{
padding:
2px;
border:
solid 1px #c1c1c1;
}
.Grid
th{
padding:
4px 2px;
color:
#fff;
background:
#363670;
border-left:
solid 1px #525252;
font-size:
0.9em;
}
</style>
Putting all together:
HTML code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" 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 () {
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
contentType: "application/json;charset=utf-8",
data: {},
dataType: "json",
success: function (data) {
$("#gvProduct").empty();
if
(data.d.length > 0) {
$("#gvProduct").append("<tr><th>Product ID</th>
<th>Product Name</th><th>Quantity Per
Unit</th><th>Unit Price</th><th>Units In
Stock</th></tr>");
for (var i = 0; i <
data.d.length; i++) {
$("#gvProduct").append("<tr><td>" +
data.d[i].ProductID
+ "</td> <td>" +
data.d[i].ProductName + "</td>
<td>" +
data.d[i].QuantityPerUnit + "</td>
<td>" +
data.d[i].UnitPrice
+ "</td> <td>" +
data.d[i].UnitsInStock + "</td></tr>");
}
}
},
error: function
(result) {
//Handling
error
}
});
});
</script>
<style type="text/css">
.Grid{
background-color:
#fff;
margin:
5px 0 10px 0;
border:
solid 1px #525252;
border-collapse:
collapse;
font-family:
Calibri;
color:
#474747;
}
.Grid
td{
padding:
2px;
border:
solid 1px #c1c1c1;
}
.Grid
th{
padding:
4px 2px;
color:
#fff;
background:
#363670;
border-left:
solid 1px #525252;
font-size:
0.9em;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvProduct" runat="server" CssClass="Grid">
</asp:GridView>
</form>
</body>
</html>
C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Configuration;
public partial class
_Default : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
if
(!IsPostBack)
{
BindDummyData();
}
}
public void BindDummyData()
{
DataTable dt = new
DataTable();
dt.Columns.Add("ProductID");
dt.Columns.Add("ProductName");
dt.Columns.Add("QuantityPerUnit");
dt.Columns.Add("UnitPrice");
dt.Columns.Add("UnitsInStock");
dt.Rows.Add();
gvProduct.DataSource = dt;
gvProduct.DataBind();
}
[WebMethod]
public static ProductDetails[] GetData()
{
List<ProductDetails> MyData = new List<ProductDetails>();
string
cmdstr = "SELECT TOP 8 ProductID,ProductName,QuantityPerUnit,UnitPrice,UnitsInStock
FROM Products";
using
(SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
{
SqlCommand cmd = new SqlCommand(cmdstr, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach
(DataRow DR in dt.Rows)
{
ProductDetails objProduct = new ProductDetails();
objProduct.ProductID = DR["ProductID"].ToString();
objProduct.ProductName = DR["ProductName"].ToString();
objProduct.QuantityPerUnit =
DR["QuantityPerUnit"].ToString();
objProduct.UnitPrice = DR["UnitPrice"].ToString();
objProduct.UnitsInStock = DR["UnitsInStock"].ToString();
MyData.Add(objProduct);
}
return
MyData.ToArray();
}
}
public class ProductDetails
{
public string ProductID { get;
set; }
public string ProductName { get;
set; }
public string QuantityPerUnit { get;
set; }
public string UnitPrice { get;
set; }
public string UnitsInStock { get;
set; }
}
}