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

Update an ASP.NET Gridview using ajax client side scripting

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
4 Feb 2015CPOL5 min read 28.3K   410   9   3
Example to show how to update an ASP.NET GridView control using Ajax JQuery client side script

Sample code in action

Introduction

There are many articles on this subject so I've tried to consolidate the many solutions into one article specifically showing how to update a ASP.NET Gridview control on the client side via Ajax without a postback. This article provides a streamlined sample of an ASP.NET grid that is updated via a client side ajax update script. When you first approach ASP.NET and Ajax solutions you'll find the heavyweight solutions provided by Microsoft or 3rd party companies trying to sell controls to the unsuspecting developer. It took me a lot of exploring with Ajax and javascript to find a solution that allows a standard Gridview control to be updated out of process on the client side using Ajax JQuery.

The technique I used was to post a standard Gridview view control to the client browser and from then on provide an updated view of the data contained in the grid by using a client side Ajax script that queries the status of each row with a server status request, passing a row identifier and returning the result of the row status to the client without using a postback.  Without Ajax the only solution would be to constantly post the Gridview back to the server to retrieve the latest row status of each element in the grid. This solution avoids the postback by using Ajax and client side javascript to ensure the users Gridview represents the current server side status of the row data without using a postback providing the user a more realtime look and feel.

Background

This solution leverages off the Ajax JQuery script library but attempts to reduce the amount of references and work required to execute an Ajax script from the client side updating an ASP.NET control. Currently without Ajax a postback to the server would be required to retrieve and updated status of the rows in the Gridview. Postbacks contain a large amount of data and provide a degraded user experience. The task at hand was to attempt a solution that did not require a postback but would update all the rows in a Gridview control with the current server side status the data represented in the grid. This simple solution is the result of that quest.

Using the code

There are two pages in the sample source code, the main page that renders the Gridview (index.aspx) and the (status.aspx) page that provides the status information back to the client side Ajax status request. I used a call center scenario as the basic concept to illustrate the sample code.

To begin I created a standard ASP.NET Gridview control ( <asp:GridView  ID="uxGrid” ... ) with some default data using XML as a datasource. This is the XML structure of the data used to create the default data in the grid.

XML
<REPORT>
<ROW><CALLID>464038540</CALLID><CALLER>Joe Bloggs</CALLER><DESCRIPTION>Complaint</DESCRIPTION><WAITTIME>0</WAITTIME><STATUS>NEW</STATUS></ROW>
<ROW><CALLID>1943703104</CALLID><CALLER>John Doe</CALLER><DESCRIPTION>Feedback</DESCRIPTION><WAITTIME>0</WAITTIME><STATUS>NEW</STATUS></ROW>
<ROW><CALLID>2115001745</CALLID><CALLER>Richard Roe</CALLER><DESCRIPTION>Complaint</DESCRIPTION><WAITTIME>0</WAITTIME><STATUS>NEW</STATUS></ROW>
<ROW><CALLID>421215934</CALLID><CALLER>Jane Doe</CALLER><DESCRIPTION>Feedback</DESCRIPTION><WAITTIME>0</WAITTIME><STATUS>NEW</STATUS></ROW> 
<ROW><CALLID>586835430</CALLID><CALLER>Wendy Roe</CALLER><DESCRIPTION>Complaint</DESCRIPTION><WAITTIME>0</WAITTIME><STATUS>NEW</STATUS></ROW>    
</REPORT>

The datasource control consumes this XML dataset.

ASP.NET
// XML Datasource used to populate the gridview control

<asp:XmlDataSource ID="srcCallCenter" Runat="server" XPath="/REPORT/ROW" EnableCaching="False" EnableViewState="False" />

Bind the XMLDatasource to the Gridview control.

ASP.NET
// Gridview control bound to the XMLDatasource 

<asp:GridView DataSourceID="srcCallCenter" ...

To call the client side javascript using an Ajax JQuery client side script the JQuery library needs to be referenced in your client side javascript code.

JavaScript
// To execute a client side postback you first need to reference the JQuery library
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

With the reference it's possible to make the call to either a webservice or, as in my example, a call to another ASP.NET page which returns a comma seperated result dataset. I chose to call an ASP.NET page for simplicity purposes. Calling a webservice would mean parsing xml which I was trying to avoid. Below is some code snippets of the client side code in the sample to illustrate the mechanism used to firstly get a reference to the gridview control and then the Ajax script used to perform to retrieve the status of the selected row.

JavaScript
// To update the gridview control I need to gain a reference to the control. With this reference I can 
// beginning traversing the Gridview on the client side and retrieve the status of each row using an
// Ajax JQuery POST command calling the Status.aspx page that retrieves the row status
 
var gridViewCtlId = '<%=uxGrid.ClientID%>'; // Get a reference to the grid view


// Further down in the client side javascript is the ajax called to retrieve the status of the relevant row in the Gridview
//Included in the success function is the code to update the relevant cell of the row whose status is being updated

$.ajax({
 url: SUrl,   // Url of my Status.aspx page
dataType: "html",  //standard HTML call to that page
data: content, 
success: function (data) { ... }  // function to handle the data returned to update to row of the Gridview control

The .ajax method calls the status.aspx with the following POST request "Status.aspx?CallID=<ID>&WaitTime=<Wait>". The Response returned by the status page is in a CSV format and is processed with the success response function by splitting the resulting data response and then updating the selected row with the status returned from the Ajax call.

JavaScript
success: function (data) {
    if (PrevCallID != CallID) {
       var checkText = grid.rows[counter].cells[4].innerHTML; //Retrieve the cell value that is going to be updated
       var waitText = grid.rows[counter].cells[3].innerHTML; //Retrieve the cell value that is going to be updated
       var result = data.split(","); //Split the comma separated result data into a string array
       if (result.length > 0) {
          var displaytext = result[1];
          var waittime = result[2];
          if (result[0] == CallID) {
            //Update the cell value with the result returned by the status.aspx call
            grid.rows[counter].cells[4].innerHTML = checkText.replace(">"+ mStatus + "<", ">" + displaytext + "<");
            if (result[1] == "OVERTIME")
               grid.rows[counter].cells[4].style.color = "Red";
            else
               grid.rows[counter].cells[4].style.color = "Black";
            grid.rows[counter].cells[3].innerHTML = waitText.replace(">" + mWaitTime + "<", ">" + waittime + "<");
            counter++;
          }
       }
       PrevCallID = CallID;
   }
   bCompleted = true; //Signal that the success function has completed so the next call can be processed
}

The bitmap above represents the final result presented to the user, all the while the ajax script is traversing the grid and providing an updated status to the user.

Summary

The solution follows the following steps:

1. Generate the Gridview from a datasource and post the page down to the client.

2. A Client side Ajax script, using a timer that fires every second, traverses the rows in the Grid control.

3. When a row is selected, a client side script fires a request to the server for the status of the selected row. 

4. The request returns data in a CSV format and the row is populate with the updated status information. 

5. The script signals that the next row can be retrieved so that the next Ajax call can be made.

Other than the initial populating of the grid on the server side the rest of the Grid management occurs on the client side enabling the Grid to take on a realtime, update look and feel. Something that is traditionally, without ajax, attained by doing a post back to the server. This solution avoids the post back and provides the user with a cleaner, realtime view of the data represented in the Grid.

The best thing to do is download the sample and deploy the code into IIS and view the sample in action.

Points of Interest

The purpose of the article is to demonstrate a simple Ajax sample using the minimum amount of code. I've found many other samples that require a lot of work to attain the same result hence my reason for publishing this article.

History

Published the article.

License

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


Written By
Architect
Australia Australia
Architecting solutions around the world.

Comments and Discussions

 
Generalcool Pin
chait30119-Feb-15 14:25
chait30119-Feb-15 14:25 
QuestionSource Code Link??? Pin
Jeff Balcerzak6-Feb-15 4:12
Jeff Balcerzak6-Feb-15 4:12 
AnswerRe: Source Code Link??? Pin
Richard Roe8-Feb-15 11:35
Richard Roe8-Feb-15 11:35 

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.