Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Clientside GridView with jQuery template and AJAX in ASP.NET

0.00/5 (No votes)
4 Jul 2013 2  
Create and Bind gridview at client side with Jquery Template and ajax in asp.net

Introduction 

Here only one thing that needs introduction is jQuery template Plugin as I said in my previous articles/tip. This article is inspired by some blog post related to jquery template. This is a simple implementation of asp.GridView like features at client side using $.ajax and $.tmpl() plugin and help of JSON data.

Source of Inspiration

As I mentioned in introduction that this is inspired version of my previous articles/tip wherein I was binding a Listview by getting JSON data with $.ajax call using $.tmpl() plugin. So this article enhanced that functionality to a level up and use it to Make a GridView(table) with some Runtime data binding.

What we are going to do 

We will use one table with only one header row. There will be two buttons one is normal HTML <input> button and other one is <asp:button>. When we click HTML button it will Bind Static data using .tmpl() plugin. Similarly <asp:button> will get data from server and bind in same way.

Note: Two different types of buttons is just for demonstration, we can have of either type.

Code Surfing 

We will start with .aspx page, because it has most of the magic.

1) We have one weird script tag with type="text/html" and associated Id.

<script id="employeeTemplate" type="text/html">
        <tr>
            <td> ${Name}</td> 
            <td>${Designation}</td>
            <td>{{if Age>30}}
                <span style='background-color:red'>Middle-aged</span>
                {{else}}
                <span style='background-color:yellow'>Still young</span>
                {{/if}}</td>
            <td>${Department}</td>
            <td> ${DataSource}</td> 
        </tr>
</script>  

Above block will act as <ItemTemplate> wherein ${Name} is similar to <%#Eval('Name')%>. Some runtime evaluation and binding also done in third <td> to change output at runtime depend upon current data, similar as we been doing in RowDataBound events.

2) Secondly, we have a <table> with id="tblEmployee" along with two buttons as

<input id="btnClient" type="button" value="Bind Grid with Client Data" onclick="BindClientSideData()" />
<asp:Button Text="Bind Grid with Server Data" runat="server" ID="btnServer" OnClientClick="javascript:return BindServerSideData()" />  
<table id="tblEmployee">
            <thead>
                <tr>
                    <th>
                        Name
                    </th>
                    <th>
                        Designation
                    </th>
                    <th>
                        Age
                    </th>
                    <th>
                        Department
                    </th>
                    <th>
                        Data Source
                    </th>
                </tr>
            </thead>
  </table>  

This table has one header row and it will act like container of our data that rendered in point 1. This is similar to <LayoutTemplate> of asp.ListView.

3) Let do some Jquery/Javascript

function BindClientSideData() {
//JSON data format
var emps = [
{ Name: "John", Designation: "Analyst", Age: 25, Department: "IT", DataSource: "Client" },
{ Name: "Matthew",Designation: "Manager",Age: 38,Department: "Accounts",DataSource: "Client" },
{ Name: "Emma",Designation: "Senior Manager",Age: 40, Department: "HR", DataSource: "Client" },
{ Name: "Sid", Designation: "Analyst", Age: 27, Department: "HR", DataSource: "Client" },
{ Name: "Tom", Designation: "Senior Analyst", Age: 35, Department: "IT", DataSource: "Client" }
];
BindTable(emps);
}

This function called by btnClient holds some static data in JSON format and calls BindTable(emps) by passing emps as argument.

function BindServerSideData() {
$.ajax({
    type: "POST",
    url: "JQueryGridTemplate.aspx/GetEmployees", //pagename.aspx/WebMethodname
    data: "{}",// Blank data
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg, status, metaData) {
        if (msg.d && msg.d.length > 0) {
            BindTable(msg.d); 
        }
    },
    error: function(ex, status) {
        //alert(ex.responseText);
        alert("error");
    },
    complete: function(eret, tytyt) {
        //alert("complete");
    }
});
return false;
} 

This function called by btnServer which makes $.ajax call to associated webpage and its method to get data in serialized format and calls BindTable(msg.d) by passing msg.d as argument in Success: block. Here 'd' is inbuilt/default properly of variable msg.

It should be noted that url can point to any thing that allows request with http.get. Target url can be some other sites/pages/WebService or WCF Rest service.

What we do with this data, Please wait for a while.

4) In previous point we were calling a method in codebehind, that is as follows

[WebMethod] 
public static object GetEmployees()
{
// This is just illustration of data fetching.
// you can have your own data logic.
// You can return strongly typed object like List, DataTable, List<Class>, Data string in JSON //format etc
List<object> emps = new List<object>();
emps.Add(new { Name= "John",Designation= "Analyst",Age= 45,Department= "IT",DataSource="Server"});
emps.Add(new { Name = "Matthew", Designation = "Manager", Age = 38, Department = "Accounts", DataSource = "Server" });
emps.Add(new { Name = "Emma", Designation = "Senior Manager", Age = 20, Department = "HR", DataSource = "Server" });
emps.Add(new { Name = "Sid", Designation = "Analyst", Age = 31, Department = "HR", DataSource = "Server" });
emps.Add(new { Name = "Tom", Designation = "Senior Analyst", Age = 25, Department = "IT", DataSource = "Server" });
    return emps;
} 

Above method is static with special [WebMethod] attribute that is returning object. Here I used some static data, I know it will never be a case. But let pardon me for sake of demo. So you can have your own logic to get data from DataStore and return it.

Things to note that it should always return strong type object such as List<ClassName>, Collections, DataTable. Some object that has defined properties/name with underlying data. In our case I am returning a collection of anonymous object.   

5) Data retuned in previous step is caught by Success: code block in case of Successful response. We pass this data to BindTable(data) function, which is as follows

 function BindTable(data) {
    // removes existing rows from table except header row
    $('#tblEmployee tr:gt(0)').remove();
    //apply tmpl plugin to <script> and append result to table
    $("#employeeTemplate").tmpl(data).appendTo("#tblEmployee");
} 

In above function we first remove all existing rows from <table> except header-row. Then we pass our data to tmpl(data) plugin and apply this plugin to <script> block that has id="employeeTemplate" and contains our row template. Finally resultant of such operation is appended to table having id="tblEmployee". And we are done with it.

Observation 

As we are using jquery.ajax call which is very light weight as compared to <asp.UpdatePanel>. As when we use updatepanel no matter which controls are going to update it sends/post data of all input fields to server and return back whole HTML that are suppose to update. Now in case of jquery.ajax it post only those data that is specified in data: { } code block of function in our case this is null. So no additional data posted to server, In addition to this we get only Serialized data from server not HTML thus it incredibly reduces network traffic and performance lagging.

Conclusion 

I/we learned a new way to do old things in very innovative and efficient way. Thanks to this site. Please comments if any doubts/queries I will try my experience best to answer you.

Folks, the world is open to tweak, Hence this code too. Please make it more usable/optimize/relevant as per your requirement. 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here