associative,arrays,client-side,caching,ajax,javascript

rou1988 8/7/2016 0

Using Associative Arrays for Client-side Caching using AJAX & Javascript

C#
 using System.Web.Script.Services;
...
[ScriptService] 
    public class DataAccess : System.Web.Services.WebService 
    { ... 
C#
 [WebMethod]
public string FetchOrders(string key)
{           
    return LoadData(key);;
}

private string LoadData(string key)
{        
    DataSet ds = new DataSet();
    ds.ReadXml(this.Context.Server.MapPath("App_Data\\northwind.xml"));
    ds.Tables["Orders"].DefaultView.RowFilter = "customerid = '"   key   "'";        
    return RenderResultTable((ds.Tables["Orders"].DefaultView));
}

private string RenderResultTable(DataView rdr)
{
    StringBuilder str = new StringBuilder();
    str.AppendLine("<table cellspacing=\"0\" cellborder=\"=0\"  
        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();
} 
JavaScript
 var cacheData = new Array(); // This is our cache
var currSel = null;
var seedData = "0BFA4D6B-DD18-48aa-A926-B9FD80BFA5B7";   
// Prime a cache item with a unique initial value 
JavaScript
 function btnFetch_onclick() 
{    
    currSel = document.getElementById("dlCustomers").value;    
    var status = document.getElementById("divStatus");
    //var svc = new DataAccess();

    if(cacheData[currSel]==null)
    {
        DataAccess.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();    
} 

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments