Populate HTML table using jQuery Template, ASP.NET web service and jQuery ajax

jQuery template provide easy way to process json data. There are several places you can use this template to populate data by making ajax call to web services.

Today we will use jQuery template to populate HTML table by making ajax call to the ASP.NET web service.

Screenshot:

We will do this in three parts:

  1. Create a class Products
  2. Create a web service file which will call database and populate list of Products
  3. ASPX file which will contain our jQuery code

First let's create a class name Products with four attributes:

public class Products

{

public int ProductID { get; set; }

public string Name { get; set; }

public double StandardCost { get; set; }

public string ProductNumber { get; set; }

 

}

 

Now we will create a web service file and uncomment [System.Web.Script.Services.ScriptService] attribute. Then in our web method we will call out adventure works database and populate list of products:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Web.Configuration;

using System.Data;

using System.Data.Sql;

using System.Data.SqlClient;

 

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]

public class ProductsLIst : System.Web.Services.WebService {

 

public ProductsLIst () {

 

}

 

[WebMethod]

public List<Products> getProducts()

{

List<Products> products = new List<Products>();

string connectionString=WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

using (SqlConnection con=new SqlConnection(connectionString))

{

SqlCommand cmd = new SqlCommand();

cmd.Connection = con;

cmd.CommandType = CommandType.Text;

cmd.CommandText = "Select ProductID,Name,StandardCost,ProductNumber from Products";

con.Open();

SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

while (rdr.Read())

{

Products prod = new Products();

prod.ProductID = Convert.ToInt32(rdr["ProductID"]);

prod.Name=rdr["Name"].ToString();

prod.StandardCost = Convert.ToDouble(rdr["StandardCost"]);

prod.ProductNumber=rdr["ProductNumber"].ToString();

products.Add(prod);

}

con.Close();

rdr = null;

cmd = null;

}

return products;

}

 

}

 

After this, we will create aspx page and add reference to:

  1. jQuery script (download linkhttp://docs.jquery.com/Downloading_jQuery )
  2. jQuery template script (download link: http://api.jquery.com/category/plugins/templates )
  3. jQuery visual studio document script (optional) (download link: http://docs.jquery.com/Downloading_jQuery)

After adding this we will create a script tag to hold template and a table to populate data:

<script id="productsTemplate" type="text/x-jquery-tmpl">

<tr>

<td>${ProductID}</td>

<td>${Name}</td>

<td>${StandardCost}</td>

<td>${ProductNumber}</td>

</tr>

</script>

<table border="1" cellpadding="2" cellspacing="3">

<thead>

<tr>

<th>Product ID</th>

<th>Product Name</th>

<th>Product Cost</th>

<th>Product Number</th>

</tr>

</thead>

<tbody id="tblProducts">

 

</tbody>

</table>

 

To make AJAX call we will use a button:

<asp:Button Text="Get Products" runat="server" ID="btnClick" />

 

Final part is the script which will make ajax call and populate data:

<script type="text/javascript">

$(document).ready(function () {

// click event on button click

$('#btnClick').click(function (e) {

// call to preventDefault() method to stop default behavior

// which in this case is postback

e.preventDefault();

// ajax call to web service

$.ajax({

// type of call

type: "POST",

// location of service along with method name

url: "ProductsLIst.asmx/getProducts",

// content type to application/json

contentType: "application/json; charset=utf-8",

// data type json

dataType: "json",

// on successful call this anonymous method

success: function (message) {

// empty any previous content present in the table

$('#tblProducts').empty();

// call to script id that contains template

// fill it with json data received from web service

// append data to table body

$('#productsTemplate').tmpl(message.d).appendTo('#tblProducts');

},

// on error show alert

error: function () { alert("Some error occured!"); }

});

});

});

</script>

 

ASPX Code:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>

<script src="Scripts/jquery.tmpl.js" type="text/javascript"></script>

<script type="text/javascript">

$(document).ready(function () {

// click event on button click

$('#btnClick').click(function (e) {

// call to preventDefault() method to stop default behavior

// which in this case is postback

e.preventDefault();

// ajax call to web service

$.ajax({

// type of call

type: "POST",

// location of service along with method name

url: "ProductsLIst.asmx/getProducts",

// content type to application/json

contentType: "application/json; charset=utf-8",

// data type json

dataType: "json",

// on successful call this anonymous method

success: function (message) {

// empty any previous content present in the table

$('#tblProducts').empty();

// call to script id that contains template

// fill it with json data received from web service

// append data to table body

$('#productsTemplate').tmpl(message.d).appendTo('#tblProducts');

},

// on error show alert

error: function () { alert("Some error occured!"); }

});

});

});

</script>

<script id="productsTemplate" type="text/x-jquery-tmpl">

<tr>

<td>${ProductID}</td>

<td>${Name}</td>

<td>${StandardCost}</td>

<td>${ProductNumber}</td>

</tr>

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Button Text="Get Products" runat="server" ID="btnClick" />

<table border="1" cellpadding="2" cellspacing="3">

<thead>

<tr>

<th>Product ID</th>

<th>Product Name</th>

<th>Product Cost</th>

<th>Product Number</th>

</tr>

</thead>

<tbody id="tblProducts">

 

</tbody>

</table>

</div>

</form>

</body>

</html>

 

Tags: , , , ,

AJAX | ASP.NET | jQuery