Associative arrays caching for Client-Side in AJAX


Introduction : Ajax (Asynchronous JavaScript and XML) is new web development technique use for the interactive website. AJAX help we can developed web application and retrieve small amount of data from web server. AJAX consist a different type of technology.

  • JavaScript.
  • XML.
  • Asynchronous Call to the server.

Array : The ArrayList object is a collection of items containing a single data value. Items are added to the ArrayList with the Add() method. The capacity of an ArrayList is the number of elements the list can hold. As elements are added to an ArrayList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling Trim to Size or by setting the Capacity property explicitly.

Step 1 : Open Visual Studio 2010.

  • Go to File->New->WebSite.
  • Select ASP.NET WebSite.
dro1.gif

Define Web Service Class :

Step 2 : Go to Solution Explorer and right-click.

  • Select Add->New Item.
  • Select Web Service.
  • Define Namespace and ScriptService.
dro2.gif

Namespace and Service :

using System.Web.Script.Services;
[ScriptService]
public class WebService : System.Web.Services.WebService
{
    public WebService()
    {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

Step 3 :  Go to Solution Explorer and right-click.

  • Select Add->New Item.
  • Select StyleSheet.
  • StyleSheet.css page open.
  • Write the below code.
dro3.gif

CSS Code :

 
.Watermark
  {
      color :Red;
   }
  .Container
  {
      background-color:#D7EBFF;
      border: 1px #D3D3D3 solid;
      padding: 10px;
      margin:10px;
   }
  .DivTable
  {
       background-color:#F0F8FF;
       border: 1px #D3D3D3 solid;
       padding: 10px;
       margin:10px;
       overflow:auto
       float:left;
       width: 335px;
       height: 163px;
       text-align:left;
   }
   .DivContents
   {
       float:left;
      white-space:nowrap;
   }

Define the Array of data for the customer and give order data.

Step 4 : Go to Solution Explorer and right-click.

  • Select Add-> New Item.
  • Select XML File.
  • Define the data value.
dro4.gif

Data :

<?xml version="1.0" encoding="utf-8" ?>
<NewDataSet> 
<Orders>
    <
OrderDate>07/08/2011</OrderDate>
    <customerid>Manish</customerid>
    <OrderID>10248</OrderID>
  </Orders>
  <
Orders>
    <
OrderDate>08/09/2011</OrderDate>
    <customerid>Akash</customerid>
    <OrderID>10249</OrderID>
 
  </Orders>
  <
Orders>
    <
OrderDate>10/08/2011</OrderDate>
    <customerid>MCN</customerid>
    <OrderID>10250</OrderID>
  </Orders>
  <
Customers>
    <
customerid>Manish</customerid>
  </Customers>
  <
Customers>
    <
customerid>Akash</customerid>
  </Customers>
  <
Customers>
    <
customerid>MCN</customerid>
  </Customers>
</
NewDataSet>

Step 5 : Now go to the Default.aspx page and drag a control from Toolbox.

  • Drag ScriptManger, UpdatePanel, Label, Button, DropDownExtender Control.

Code :
<body style="text-align:center;" onload="OnBodyLoad()" onkeypress="return OnKeyPress();">
      <form id="form1" style="text-align:center;" runat="server">
           <asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="0"   ScriptMode="Release" >
               <Services>
                   <asp:ServiceReference Path="WebService.asmx" />               
               </Services>
           </asp:ScriptManager>
           <div id="MainContainer" style="float:left; width: 593px; height: 252px;" class="Container">
               <h3 style="text-align: center"> Arrays for Client-side Caching using AJAX &amp; Javascript this is my AJAX</h3> 
              <div id="MainContent" style="float:left;width:200px;text-align:left;">
                   <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                       <ContentTemplate>       
                           <asp:Label ID="Label1" runat="server" Text="Select a Customer:"></asp:Label>
                           <asp:DropDownList  ID="dlCustomers" runat="server" Width="198px">
                           </asp:DropDownList>                          
                       </ContentTemplate>
                   </asp:UpdatePanel>
                  &nbsp;<br />
                  <span id="divStatus" style="width: 198px; height: 19px;color:Navy;"></span><br />
                  <input type="button"  style="margin-top:10px; height: 24px; width: 72px;"
                       value="Fetch" id="btnFetch"  onclick="return btnFetch_onclick()"
                         /></div>
              <asp:Panel ID="ajaxContent" runat="server" CssClass="DivTable">               
              </asp:Panel>
         </div>
      <asp:DropShadowExtender ID="DropShadowExtender2" runat="server" Opacity="0.2" TargetControlID="ajaxContent"
              Width="3">
      </asp:DropShadowExtender>
     </form
>

Step 6 : Now go to the WebService.cs and define the WebMethod.

[WebMethod] :

[WebMethod]
    public string FetchOrders(string key)
    {
        string results = LoadData(key);
        return results;
    }
    private string RenderResultTable(DataView rdr)
    {
        StringBuilder str = new StringBuilder();
        str.AppendLine("<table cellspacing=\"1\" cellborder=\"=1\" cellpadding=\"5\">");
        str.AppendLine("<tr><td><b>Order Date</b></td><td><b>Order ID</b></td></tr>");
        foreach (DataRowView drv in rdr)
        {
            str.AppendLine("<tr>");
            str.AppendFormat("<td>{0}</td> <td>{1}</td>", drv["OrderDate"], drv["OrderID"]);
            str.AppendLine("</tr>");
        }
        str.AppendLine("</table>");
        return str.ToString();
    }
    private string LoadData(string key)
    {       
         DataSet ds = new DataSet();
         ds.ReadXml(this.Context.Server.MapPath("App_Data/XMLFile.xml"));
         //DataView dv = ds.Tables["Orders"].DefaultView;
         //dv.RowFilter = "customerid = '" + key + "'";
         ds.Tables["Orders"].DefaultView.RowFilter = "customerid = '" + key + "'";       
         return RenderResultTable((ds.Tables["Orders"].DefaultView));
    }
}

Step 7 : Now go to the Default.aspx.cs option and write the below code in the page load event.

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;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("App_Data/XMLFile.xml"));
           DataTable dt = ds.Tables["Customers"];
          dlCustomers.DataSource = dt;
           dlCustomers.DataTextField = "customerid";
           dlCustomers.DataValueField = "customerid";
         dlCustomers.DataBind(); 
    }
}

Step 8 : Now go to Default.aspx page and select Design option.

  • Click in Fetch Button and write the below code.

Code :

function btnFetch_onclick() {
       currSel = document.getElementById("dlCustomers").value;
           var status = document.getElementById("divStatus");
           //var svc = new DataAccess();
           if (cacheData[currSel] == null) {
               WebService.FetchOrders(currSel, OnCompleteCallback, OnErrorCallback, OnTimeOutCallback);
               cacheData[currSel] = seedData;
               status.innerHTML = "[Live Result]";
           }
           else {
               status.innerHTML = "[Cached Result]";
               var cacheobject = FetchDataFromCache(currSel);
               RenderData(cacheobject);
           }
           document.getElementById("dlCustomers").focus();
       }
       function FetchDataFromCache(objectkey) {
           return cacheData[objectkey];
       }
       function RenderData(data) {
           var cndiv = document.getElementById("ajaxContent");
           cndiv.style.display = "";
           cndiv.innerHTML = String(data);
       }
       function OnCompleteCallback(retResult) {
           if (cacheData[currSel] == seedData) {
               cacheData[currSel] = retResult;
           }
           RenderData(retResult);
       }
       function OnTimeOutCallback(retResult) {
           alert("AJAX Callback Timeout occurred.");
       }
       function OnErrorCallback(retResult) {
           alert("AJAX Callback Error occurred.");
       }
       function OnBodyLoad() {
           document.getElementById("dlCustomers").focus();
       }
       function OnKeyPress() {
           if (event.keyCode == 13)
               btnFetch_onclick();
       }

Step 9 : Now retrieve the data and call the WebService then declare a variable.

Variable :

    var cacheData = new Array();
    var currSel = null;
    var seedData = "0BFA4D6B-DD18-48aa-A926-B9FD80BFA5B7";

Step 10 : Now press F5 and run the application.

dro5.gif

Step 11 : Now we select any name from DropDownExtender and click in Fetch Button then fetch the record for particular customer.

dro6.gif


Similar Articles