Define a cache for just part of a view is not possible (so far) but you can simulate it by implementing an output cache to a partial view (an ascx control view) and add this partial view declaratively using the same syntax we are used to write when adding regular user controls (ascx controls) to web forms.
Create a new ASP.NET MVC Web Application;
When it’s done, right-click the folder Home under Views and select Add > View;
Name the new view MyCachedPartialView and mark the Create a partial view (.ascx) checkbox. Click Add when it’s done;
Open the partial view and add an output cache directive to refresh the content every 10 seconds and that does not refresh when different parameters are passed as shown below:
<%@ OutputCache Duration=”10″ VaryByParam=”none” %>
Render the current date and time to the partial view body:
<p>Partial View: <%= DateTime.Now %></p>
Open the Index view under Views > Home folder;
As the same way than web forms applications, you can drag a partial view control onto the view surface that will add a register declarative and a control markup. To perform that switch the Index view to design mode and from the Solution Explorer drag the MyCachedPartialView control we’ve just created onto the view surface. The markup generated will be:
// Top of view
<%@ Register src=”MyCachedPartialView.ascx” tagname=”MyCachedPartialView” tagprefix=”uc1″ %>
// Control region
<uc1:MyCachedPartialView ID=”MyCachedPartialView1″ runat=”server” />
To make our test easier to understand, render the current date and time to the Index view just before the partial view control region:
<p>Index View: <%= DateTime.Now %></p>
Build and run the application. When the dialog Debugging Not Enabled is displayed, just click OK;
When the application is displayed, press the F5 key repeatedly on the keyboard and realize that the date and time just changes for the Index View. Only after the 10 seconds elapses the date and time will be refreshed on the Partial View.
Important: The partial cache only works when you add the partial view as a strong reference. If you try to render your partial view by using the RenderPartial Html Helper method it is not going to work since you request a brand new control to be rendered every time a View is refreshed.
Keep this tip in mind and you may save a lot of render time and make your application to have a faster response.