当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

I'm just starting to look in to caching to improve performance and have a question about caching for an AJAX call.

I have a action which is used to query twitter and then return the results. At the moment when a user presses a button it loads a rotating gif whilst it goes off to the action to do the query and then return a partial view. jQuery then updates a div with the HTML response from the view. Normally this takes around 5 secs. They then have a more button which goes off to get more results.

What will happen if I put the CachingAttribute over this action? I know I can try it but I just want the technical side of things explained.

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);

}

网友答案:

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

Now on the server side you could decorate your controller action with the [OutputCache] which will allow you to define different caching strategies. You could keep a cache on the server, on downstream proxy servers, or on the client. You could also manage different expiration policies.

So let's illustrate this by 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 each request but the action won't be executed if there's a cached version and will directly served from this cache. 10 seconds later from the first request which hit the controller action the cache will expire and the same process repeats.

分享给朋友:
您可能感兴趣的文章:
随机阅读: