Geeks With Blogs

AzamSharp Some day I will know everything. I hope that day never comes.

I am reading this awesome book "Building a Web 2.0 Portal with ASP.NET 3.5" by Omar Al Zabir. Omar talks about caching the Ajax requests on the browser cache. This will improve the performance since the request will be handled directly from the browser cache without contacting the server. Let's take a very simple example. Let's say you have a DropDownList which displays the categories .When the user selects the categories you display all the products in that category. You are making an Ajax call to fetch all the products from the database. If you are not caching the Ajax request then you will have to contact the server continuously to get the products.

Let's take a look at the implementation of the JavaScript loadProducts function.

function loadProducts(categoryId)
{
    VirtualTutoringRoomWebApps.VirtualRoomService.GetProducts(categoryId, function(result)
    {
        $get("div1").innerHTML = result;
    });
   
}

The loadProducts function takes categoryId as a parameter. Now, check out the implementation of the GetProducts method in the VirtualRoomService webservice.

 [WebMethod]
        public string GetProducts(int categoryId)
        {

            string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";
            SqlConnection conn = new SqlConnection(connectionString);

            SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Products WHERE CategoryID = " + categoryId, conn);
            DataSet ds = new DataSet();
            ad.Fill(ds);

            GridView gv = new GridView();
            gv.DataSource = ds;
            gv.DataBind();

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            gv.RenderControl(htw);
            return sb.ToString();
        }

Now, let's add the code for caching the Ajax request.

  [WebMethod]
        [ScriptMethod(UseHttpGet=true)]
        public string GetProducts(int categoryId)
        {

            TimeSpan cacheDuration = TimeSpan.FromMinutes(1);

            FieldInfo maxAge = Context.Response.Cache.GetType().GetField("_maxAge",
                BindingFlags.Instance | BindingFlags.NonPublic);
            maxAge.SetValue(Context.Response.Cache, cacheDuration);

            Context.Response.Cache.SetCacheability(HttpCacheability.Public);
            Context.Response.Cache.SetExpires(DateTime.Now.Add(cacheDuration));
            Context.Response.Cache.AppendCacheExtension(
                    "must-revalidate, proxy-revalidate");

            string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";
            SqlConnection conn = new SqlConnection(connectionString);

            SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Products WHERE CategoryID = " + categoryId, conn);
            DataSet ds = new DataSet();
            ad.Fill(ds);

            GridView gv = new GridView();
            gv.DataSource = ds;
            gv.DataBind();

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            gv.RenderControl(htw);
            return sb.ToString();
        }

The method is decorated with the ScriptMethod attribute which indicates that the request will be HttpGet. Only, Http Get requests can be cached. The bold lines performs the caching of the request on the browser cache. Next, time when you select that category you will get the result from the browser cache which will be very fast.   

You can use Fiddler to see what data is transfering and you will be amazed that when the request is cached no data is transferred since the client is getting the data from the browser cache and not from the server.

Posted on Sunday, February 17, 2008 4:38 PM | Back to top


Comments on this post: Caching Ajax Requests on the Browser

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net