How does ASP.NET MVC caching work for an AJAX request?

I'm just starting to look for caching to improve performance and ask a question about caching for AJAX calls.

I have an action that is used to request a twitter and then returns the results. At that moment, when the user clicks the button, he loads the rotating gif, while he goes to the action to execute the request, and then returns a partial view. JQuery then updates the div with the HTML response from the view. It usually takes about 5 seconds. Then they have another button that goes away to get more results.

What happens if I put a CachingAttribute on this action? I know that I can try, but I just want to explain the technical side of things.

thanks

Here is my Javascript:

$('#blogEntryList #moreLink').live("click", function() { $('#morespan').toggle(); $('#loader').toggle(); $.get($(this).attr("href"), function(response) { $('#blogEntryList ol').append($("ol", response).html()); $('#blogEntryList #moreLink').replaceWith($("#moreLink", response)); $('#loader').hide(); $('#morespan').show(); }); return false; }); 

Here is my modified action:

 [OutputCache( Location = OutputCacheLocation.Server, Duration = 100, VaryByParam = "")] public ActionResult BlogPosts(int? entryCount) { if (!entryCount.HasValue) entryCount = defaultEntryCount; int page = entryCount.Value / defaultEntryCount; IEnumerable<BlogData> pagedEntries = GetLatestEntries(page, defaultEntryCount); if (entryCount < totalItems) AddMoreUrlToViewData(entryCount.Value); return View("BlogEntries", pagedEntries); } 
+7
caching asp.net-mvc asp.net-mvc-2
source share
1 answer

Here's how it works: assuming caching is not specified on the server side, by default GET requests will be cached by the browser, and POST requests will not be cached unless you specify the cache: true attribute when sending AJAX requests, which allows you to override the caching strategy customers.

Now on the server side, you can decorate your action with [OutputCache] which allows you to define various caching strategies. You can store the cache on the server, on proxies, or on the client. You can also manage various expiration policies.

So let's illustrate this with an example:

 [OutputCache( Location = OutputCacheLocation.Server, Duration = 10, VaryByParam = "")] public ActionResult Hello() { return Content(DateTime.Now.ToLongTimeString(), "text/plain"); } 

And on the client side:

 $.ajax({ url: '/home/hello', type: 'post', success: function (result) { alert(result); } }); 

The result of this controller action will be cached on the server for 10 seconds. This means that the server will be hit on every request, but the action will not be performed if there is a cached version and will be directly served from this cache. 10 seconds after the first request that falls into the action of the controller, the cache expires and the same process repeats.

+11
source share

All Articles