views:

385

answers:

1

Hi guys,

I've recently decided to try out MVC 2 and coming from a webforms background, I'm having a little trouble trying to figure out the best practice solution to caching data provided to a partial view (user control).

In my webforms application, I have an AccountSummary.aspx page, which has a Booking.ascx control. Booking.ascx had output caching of 300 seconds and in the Page_Load of AccountSummary.aspx, I used to check if the control was null, and if not, pass it a UserId. Then in the code-behind of the Booking.ascx, I used to make a data access call to fetch all the bookings, thus a call to fetch the bookings was made at most once every 300 seconds.

I would like to achieve the same in MVC2, but I can't seem to find the best way of achieving this because all the examples on the web seem to pass the data to the user control in the RenderPartial HTML helper method (which I don't want because on every page load I would have to pass the booking info which is going to kill my database!)

Please advise :-)

Cheers, A.

+3  A: 

There is no simple mechanism for view-level caching in ASP.NET MVC 2.

There are some clever tricks to exploit the output caching in ASP.NET, like Donut Caching and Donut Hole Caching, but they both violate the MVC pattern (by making the DAL spill over into the views, for example), are very tricky to get right, and exhibit virtually undocumented behavior. (See the comments in the blog posts and other posts here on SO for more information.)

The short answer is that view-level caching (i.e. caching a partial view or a view, as opposed to an action method) is a trip you do not want to embark on if you are new to ASP.NET MVC. Hence, you should cache in your DAL instead, or on your action methods.

In your example, you could have a OutputCacheAttribute on an action method that returns a partial view with the booking list, or you could use the System.Web.Cache to cache the booking list when retrieving it in your DAL.

bzlm
Thanks very much, seems like I was looking at the problem from the wrong angel. Just out of interest, is System.Web.Cache a scalable mechanism of caching? With my web application, I could be storing about 100,000 LINQ-to-SQL objects at any one time.
Astrofaes
System.Web.Cache is *very* performant and scalable. It does not support distribution, though. If you are caching Linq-To-SQL objects, beware of accidentally caching EntityRefs and EntitySets.
bzlm