views:

966

answers:

3

How would you access the cache from a jQuery ajax call?

I'm using jquery to do some data verification and quick data access. I have a static web-method that jquery is calling via json to return a value. I don't want to call to the database everytime so I'd like to cache the data I'm hitting, but I can't determine how to call the asp.net cache from within javascript, or a static method.

I'd like to send the page object through to the static method, which would allow me to access page.cache, but don't know how. Barring that, maybe a way to access the cache from javascript itself?

A: 

Javascript is client side, the Cache is on the Server Side, so you need to do a callback to a method in your asp.net application, that returns the content of the cache.

The ASP.NET Cache API is really good, you can use Cache["Key"] to get the cached content that you like. Read more here : http://msdn.microsoft.com/en-us/library/ms972379.aspx

Filip Ekberg
+1  A: 

I think calling a PageMethod may be the best you can really do, if you really want to do this:

http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

BobbyShaftoe
+11  A: 

Cache is shared per app domain - not per Page. Page just has a convenience property of Page.Cache to get the current Cache, which means you can just do Cache["key"] from a method in a page.

As you've noticed, if you're in a static method - then you have no Page instance, and you have no Page.Cache property. So, you need to use HttpContext.Cache. But, wait - you have no HttpContext instance either! That's ok, the currently executing instance is stored at the static property of HttpContext.Current.

So - to answer your question - in a static method, use HttpContext.Current.Cache. BTW, you can also access the Request and Response properties from there.

Mark Brackett
You're my savior! That's exactly what I wanted to know. I knew there had to be a way to get to the cache, but couldn't figure out how. Many many thanks!
theo
Also agree, thanks for the answer.
Scott
Yup, thanks for this.