Partial Caching for Content in a Custom Sitefinity CMS Widget

September 09, 2013 Digital Experience
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.

Patrick Dunn