KodeKreachor
KodeKreachor

Reputation: 8882

Cache MVC PartialView returned from ajax get

Is is possible to cache an MVC partial view being returned from an ajax get request?

Here's my scenario. I'm calling a url which points to a controller method that returns a partial view:

Controller method:

public ActionResult SignIn()
{
    return View("SignIn");
}

Ajax request to get the view:

$.get('/Home/SignIn', function (data) { $('.content').html(data); });

Is it possible to cache my "SignIn" view so that each time the user clicks it, it doesn't have to go back to the server to fetch the view from the controller again?

Upvotes: 0

Views: 389

Answers (2)

likestoski
likestoski

Reputation: 1911

Maybe store the results in a locally declared javascript variable. For instance (pseudo code) ..

var PageState = {};
PageState.CachedView = function(){ $.get('/Home/SignIn', function (data) { $('.content').html(data); }); }

  $(document).ready(function(){
    $("#myButton").click(function(){ $("#myDialogContents").html(PageState.CachedView);
  });

One thing I would watch out for is to clear the text boxes when the cached html is shown unless you want the the username preserved.

Upvotes: 1

Ecnalyr
Ecnalyr

Reputation: 5802

This would cache the view on the server - limiting server load -

Change your action to:

public class Home : Controller
{
    // You can change this duration to whatever you want (in seconds)
    [OutputCache(Duration = 6000)] 
    public ActionResult SignIn()
    {
        return View("SignIn");
    }
}

Your AJAX request remains the same:

$.get('/Home/SignIn', function (data) { $('.content').html(data); });

Upvotes: 3

Related Questions