Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC output cache with dynamic fragment

How could I cache an entire page except a bit at the top which says something along the lines of "Welcome back, Matt! | Log Out" if the user is logged in and so-on?

I'm using ASP.NET MVC 2.

like image 820
Matthew H Avatar asked Jul 26 '10 22:07

Matthew H


2 Answers

What you are trying to achieve is called donut-caching or cache substitution. As of ASP.NET MVC 2 there is no built in helper to support this scenario. As much as I know it was a planned feature in MVC v.1 but it was dropped somewhere in the way to the release. For more info check this links http://haacked.com/archive/2008/11/05/donut-caching-in-asp.net-mvc.aspx, Is Donut Caching working properly with ASP.NET MVC?. VaryByParam option that is mentioned by Oleg here is not a good idea in your case. If you have VaryByParam a different version of the page will be put in the cache for every different value of the parameter (in your case for every user-name). Personally I would think of caching the data, not the whole output of the page.

like image 128
Branislav Abadjimarinov Avatar answered Sep 26 '22 02:09

Branislav Abadjimarinov


Probably helps

<%@ OutputCache Duration="15" VaryByParam="*" %>

or with some other value for the VaryByParam. See http://msdn.microsoft.com/en-us/library/hdxfb6cy.aspx, http://blog.maartenballiauw.be/post/2008/06/Creating-an-ASPNET-MVC-OutputCache-ActionFilterAttribute.aspx and http://blogs.microsoft.co.il/blogs/gilf/archive/2010/07/18/asp-net-output-cache-provider.aspx.

Moreover, if you have the start page which is not user depended, it is possible to replace the start page with a very static welcome page with the empty field (hidden div) instead of "Welcome back, Matt! | Log Out". After that an ajax request for filling of the user name can be started at the client side. This kind of the welcome page page can be very good cached.

like image 24
Oleg Avatar answered Sep 27 '22 02:09

Oleg