asp.net MVC browser caching problem with jquery-practical tips

Source: Internet
Author: User
Tags http post

Introduced

Although jquery provides a good support for caching in the browser's Ajax invocation, it is important to understand how to use the HTTP protocol efficiently.

The first thing to do is to support HTTP get on the server side, and define different URLs to output different data (the corresponding action in MVC). If you want to use the same address to get different data, that is not true, an HTTP post is not good because the post cannot be cached. Many developers use post for 2 main reasons: clear that the data cannot be cached, or avoid JSON attacks (which can be invaded when JSON returns an array).

Cache interpretation

The AJAX approach in the JQuery Global object provides options to support caching and conditional gets functionality.

$.ajax ({
  ifmodified: [True|false],
  cache: [True|false],
});

The ifmodified option defines whether the conditional gets feature is supported when Ajax calls. jquery automatically handles the header value returned by the server, named Last-modified, and then sends the if-modified-since in the header in the subsequent request. This requires our MVC controller to implement the conditional gets function. The Conditional gets feature is used in the HTTP cache context to validate expired entries in the cache. If jquery thinks an entry has expired, it first asks the server to conditional the entry using the gets feature, and if the server returns status code 304 (not modified), jquery will reuse the item in the cache, so We can save a lot of traffic to download the page content.

The cache option basically overwrites all the cache-related settings in the HTTP header returned by the server, and if the cache option is set to False, jquery will append a timestamp to the URL after the request to distinguish the URL from the previous address. This is true. The content of the request is up to date, which means that every time the browser receives a new address, the natural return is the latest data.

Let's take a look at a few scenarios:

Set No-cache in server-side response

The server-side is king, and jquery is powerless if the server-side explicitly defines a response response that cannot be cached. The cache options in Ajax will be ignored.

JS Code:

$ (' #nocache '). Click (function () {
  $.ajax ({
    URL: '/home/nocache ',
    ifmodified:false,
    cache:true,
    success:function (data, status, XHR) {
      $ (' #content '). HTML (data.count);
    }
  });


C # code:

Public ActionResult NoCache ()
{
  //Disable caching
  Response.Cache.SetCacheability (Httpcacheability.nocache);
  Return Json (New {count = count++}, jsonrequestbehavior.allowget);
}

Set expiration time in server-side response

The server-side set expiration time is used to cache data, which is cached by the client based on its expiration date.

JS Code:

$ (' #expires '). Click (function () {
  $.ajax ({
    URL: '/home/expires ',
    ifmodified:false,
    cache:true,
    success:function (data, status, XHR) {
      $ (' #content '). HTML (data.count);
    }
  });


C # code:

Public ActionResult Expires ()
{
  Response.Cache.SetExpires (DateTime.Now.AddSeconds (5));
  Return Json (New {count = count++}, jsonrequestbehavior.allowget);
}

The client never caches data

The client decides to have the most up-to-date data (not using caching) every time, that is, the cache option in Ajaxi is set to false, and regardless of how the server side is defined, jquery each request URL address is unique, with the goal of getting the latest content each time.

JS Code:

$ (' #expires_nocache '). Click (function () {
  $.ajax ({
    URL: '/home/expires ',
    ifmodified:false,
    cache: False,//Here is the key
    success:function (data, status, XHR) {
      $ (' #content '). HTML (data.count
    )
  ;
}});

C # code:

Public ActionResult Expires ()
{
  //No server-side settings are useless
  Response.Cache.SetExpires (DateTime.Now.AddSeconds (5));
  Return Json (New {count = count++}, jsonrequestbehavior.allowget);
}

Server side and client use conditional gets function to validate cached data

The client places the entries in the cache and validates them after they expire. The server side must implement conditional get functionality (using the header of Etags or last modified).

JS Code:

$ (' #expires_conditional '). Click (function () {
  $.ajax ({
    URL: '/home/expireswithconditional '),
    Ifmodified:true,//Here is the key
    cache:true,
    success:function (data, status, XHR) {
      $ (' #content '). HTML ( Data.count);}};


C # code:

Public ActionResult expireswithconditional ()
{
  if (request.headers["if-modified-since"]!= null && Count% 2 = 0)
  {return
    new Httpstatuscoderesult ((int) httpstatuscode.notmodified);
  }

  Response.Cache.SetExpires (DateTime.Now.AddSeconds (5));
  Response.Cache.SetLastModified (DateTime.Now);

  Return Json (New {count = count++}, jsonrequestbehavior.allowget);
}

The code in the MVC action above is just an example (not real code), and in a real implementation, the server side should be able to know whether the data has been modified since the last response.

Summarize

In detail through these 4 scenes, you should understand the AJAX request caching technology, I will not do summary.

Original English from: http://weblogs.asp.net/cibrax/archive/2012/02/10/hacking-the-browser-cache-with-jquery-and-asp-net-mvc.aspx

The above article asp.net mvc in the use of jquery browser caching problem is small to share all the content of the whole, hope to give you a reference, but also hope that we support cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.