user948365
user948365

Reputation:

MVC 3 Prevent partial View to cache

I am using MVC 3 with razor. I have some partial views which calling from main view. In Partial view i want to show some DB values. When i am changing DB values it shows old values from cache. So how i can stop cache on Partial Views?

 @Html.Partial("_myPartialView", Model)

thx

Upvotes: 1

Views: 3905

Answers (4)

Jeff
Jeff

Reputation: 27

Depending on setup, maybe one possible approach to disable caching on a partial view is to break it out as a separate client-side call, ie into jQuery/Ajax.

Otherwise how about this variation on the theme.

Took a little while to figure this one out after getting back into MVC. Just put the cache setting directly in the partial header view. As in when displaying the user name. No need for global or server-side code.

Only problem is once a page is cached, it will not refresh right away after login. But we keep the speed when needed in the initial browsing for products. Ok trade off in our case.

@if ( Request.IsAuthenticated)
{
        @* when we are authenticated, don't cache any more! *@
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
HttpContext.Current.Response.Cache.SetNoServerCaching();
        @*@Html.Raw(DateTime.Now.ToString())*@
@Html.ActionLink("Welcome " + ( String.IsNullOrEmpty(((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirstValue("UserName")) ? User.Identity.Name : ((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirstValue("UserName")), "Index", "Manage", routeValues: new { Area = "Store" }, htmlAttributes: new { title = "Manage"})
}
else
{
}

Upvotes: 0

Har
Har

Reputation: 5004

 $(function () {
 $.ajaxSetup ({
      // Disable caching of AJAX responses
      cache: false }); 
)};

That should do it!

Upvotes: 1

Adam Tuliper
Adam Tuliper

Reputation: 30152

Your code is likely caching EVERYTHING (could be browser cache by default) so you really want donut hole caching which is being worked on. Check out: http://www.devtrends.co.uk/blog/donut-output-caching-in-asp.net-mvc-3

Upvotes: 2

PanJanek
PanJanek

Reputation: 6675

The code above does not use cache as default. If you use

@Html.Partial("_myPartialView", Model)

It renders the _myPartialView using data from Model object without any cache. Your problem has to be caused by something else. Maybe the data retrieveing code that constructs the Model object use some data-layer cache? Posting more code would be helpful.

Upvotes: 0

Related Questions