Categories
Bloggers
Blogs RSS feed

Partial Caching for Content in a Custom Sitefinity CMS Widget

by Patrick Dunn
There are times in your development cycle where you may want to exclude certain items from the page cache. You may be inclined to turn off caching for that specific page or fiddle with post cache substitution. However, when it comes to a simple widget you'd probably prefer a simple solution.

In this instance we can use the asp substitution control to ensure our dynamic data is loaded properly even when the cached version of the page is requested.

Here's an easy example where we use this method to prevent the current culture display name from being cached.

protected void Page_Load(object sender, EventArgs e)
{
    GetLanguageName(this.Context);
}
  
public static string GetLanguageName(HttpContext context)
{
    var currentCulture = Thread.CurrentThread.CurrentCulture;
    return currentCulture.DisplayName;
}

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="LoginText.ascx.cs" Inherits="SitefinityWebApp.Custom.LoginText" %>
<asp:substitution id="Substitution1"
 methodname="GetLanguageName"
 runat="server">
</asp:substitution>

In the template of the widget we specify our method name in the substitution control. In the .cs file we have a method with the matching name that returns a value to be displayed. The method GetLanguageName - in this case - will be called every time returning the non-cached value for the substitution control.

This sort of approach is good when you need to have a small amount of dynamic data show on a cached page. For instance, your login/logout status or the current UI culture. You don't want to show a logged in status to a user who is logged out and you wouldn't want to display a label for the incorrect culture in a widget that otherwise can be cached.

For more information about the asp substitution control check out the MSDN documentation.

Happy coding.

2 comments

Leave a comment
  1. Craig Odar Sep 09, 2013
    Is there anything similar we can do for MVC widgets?
  2. Patrick Sep 09, 2013
    Hey Craig, sure thing.

    [OutputCache(Duration = 3600)]
    public ActionResult Index()
    {
    return View();
    }

    @Html.Action("Index", "CONTROLLERNAME")


    ----


    Even easier!

    Leave a comment