AJAX is on my mind for quite some time now. I was implementing a functionality just like google suggest using AJAX.NET library when I ran into an interesting problem.
Basically I have a method named FillList this method is marked with [Ajax.Method] attribute and hence has the power of being called from the client side. FillList method in turn calls GetDataSet method which returns the DataSet. Here is the implementation of the GetDataSet method.
private DataSet GetDataSet()
{
DataSet ds = null;
string query = @"SELECT * FROM tblPerson";
SqlConnection myConnection = new SqlConnection(GetConnectionString());
SqlDataAdapter ad = new SqlDataAdapter(query,myConnection);
ds = new DataSet();
ad.Fill(ds,"tblPerson");
ViewState["MyDataSet"] = ds;
return ds;
}
I know the implementation of the method is bad (performance wise) as I am accessing the database on every call. This means that every key the user presses the method GetDataSet will be called. So, I tried to implement the Caching on the DataSet.
I change the method to this:
private DataSet GetDataSet()
{
DataSet ds = null;
if(Cache["MyDataSet"] != null)
{
ds = (DataSet) Cache["MyDataSet"];
}
else
{
string query = @"SELECT * FROM tblPerson";
SqlConnection myConnection = new SqlConnection(GetConnectionString());
SqlDataAdapter ad = new SqlDataAdapter(query,myConnection);
ds = new DataSet();
ad.Fill(ds,"tblPerson");
// DataSet is valid for 10 minutes and after that it expires
Cache.Insert("MyDataSet",ds,null,DateTime.Now.AddMinutes(10),TimeSpan.Zero);
}
return ds;
}
Now according to me this should fix the problem of accessing the database again and again but this introduces another juicy nugget. If you try the above code (The one that uses Caching) you will see that the code always returns "null". There is no error generated on the server side as well as the client side.
The Reason:
The reason is that AJAX is not able to access the Cache object since its created and maintained on the server. AJAX is used to make the server side calls NOT to access the variables created on the server.
You can however cache the AJAX method:
[Ajax.AjaxMethod(30)] // This will be cached for 30 seconds