Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to cache user details in a partial in mvc

In the header of every page I am showing Username and User points. This is being pulled in from a partial (which gets the points from the database).

How can I cache this partial so that across each page I avoid having to check the database for the users points, and after 24hrs it can look again (cache expires). Also if the user logs off and someone else logs in it will show the new username and points (not the previously cached one).

like image 696
raklos Avatar asked Feb 14 '11 16:02

raklos


People also ask

How do you caching in MVC?

In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action. Output caching basically allows you to store the output of a particular controller in the memory.

What is partial page caching?

Partial page caching enables you to cache portion of a page. It is also called as control caching or fragment caching. Normally partial caching is performed using the "User Control". You can do caching with the help of user control as same as page output caching but you have to do caching in user control.

How can store data in cache in ASP.NET MVC?

Store data into Cache in ASP.NET MVC in ASP.NET MVC Above action method first checks for the null value in HttpContext. Cache[“MyDate”] and it its null then saves current date in the Cache. Next line simply keep the data from the Cache into ViewBag. DateTime.

What are the different caching techniques available in .NET MVC?

Any (Default)- Content is cached in three locations- the Web Server, any proxy Servers and the Web Browser. Client- Content is cached on the Web Browser. Server- Content is cached on the Web Server. ServerAndClient- Content is cached on the Web Server and the Web Browser.


1 Answers

This is user specific so I would store it in a persistent cookie. So when a user authenticates you could query the database to fetch the required information and issue a persistent cookie which will expire in 24h. Then in the partial you would check whether the cookie exists and fetch the necessary data from this cookie and if the cookie doesn't exist query the database and reemit the cookie. When the user logs out you could remove the cookie although that's not strictly necessary because when he logs back in (with the same or other username) you would query the database once again and reemit the cookie.

And because we live in 2011 and HTML5 is knocking on our doors instead of cookies I would probably use the HTML5 Local Storage and if the browser doesn't support it fallback to cookies.

like image 134
Darin Dimitrov Avatar answered Oct 01 '22 00:10

Darin Dimitrov