Saturday, February 1, 2014

Binding returned data from an Ajax call to a Gridview

First, I have to say this was one of my most frustrating functions I've ever created. The biggest problem I faced was trying to get the data from the Ajax call to bind to the Gridview. As you'll see in this example, once the data returns, I loop through the xml and append a table row to the Gridview.


You'll need the JQuery reference in the head section.

 <script src ="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type ="text/javascript">

For this first function you'll need to change the url in the ajax call to either the page your creating the Ajax call or the page your getting the post from which can also be a web service or handler. Then don't forget to set the method name after the page or web service your calling.

 function Button1_onclick() {
    $.ajax({
            type: "POST",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            url: "AjaxTest.aspx/GetTransactionData",
            dataType: "xml",
            success: OnSuccess,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
              $("#errmsg").ajaxError(function (event, request, settings) {
              $(this).append("<li>Error requesting page " + settings.url + "</li>");
           });
         }
      });
           return false;
    }

The next function will loop through the returned xml and append a table row for each row found in the xml to the Gridview.

 function OnSuccess(xml) {
   debugger;
    try {
         $(xml).find('Table1').each(function () {
          var id_text = $(this).find('ID').text();
          var name_text = $(this).find('Description').text();

          $('#<%=GridView1.ClientID %>').append("<tr><td>" + id_text + "</td><td>" + id_text + "</td</tr>");
        });
        }
    catch (err) {
        var txt = "There was an error on this page.\n\n";
        txt += "Error description: " + err.description + "\n\n";
        txt += "Click OK to continue.\n\n";
        alert(txt);
       }
     }

Below is the form example used to initiate the ajax call.

 <input id="Button1" type="button" value="Get XML" onclick="return Button1_onclick()" />
            <asp:GridView ID="GridView1" runat="server"></asp:GridView>

Finally, this is where you'll fill the data that gets returned to the client side. You'll need to add a WebMethod to your ".CS" page then create your data table and fill it from either a direct database call or web service to return the xml. In the example below, I'm creating my initial data table columns in the Page_Load so that when the Ajax call returns, it knows what columns are mapped to the Gridview.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
protected void Page_Load(object sender, EventArgs e)
    {
        DataTable table = new DataTable();
        table.Columns.Add("ID");
        table.Columns.Add("Description");
        table.Rows.Add();
        GridView1.DataSource = table;
        GridView1.DataBind();
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
    public static string GetTransactionData()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Description");

        dt.Rows.Add("1", "Description 1");
        dt.Rows.Add("2", "Description 2");
        dt.Rows.Add("3", "Description 3");
        dt.Rows.Add("4", "Description 4");
        dt.Rows.Add("5", "Description 5");

        DataSet m_dsDataSet = new DataSet("pageDataSet");

        m_dsDataSet.Tables.Add(dt);

        string strXml = m_dsDataSet.GetXml();
        return strXml;
    }

No comments:

Post a Comment