Sitecore provides a suite of web controls for Web Forms development within the Sitecore.Web.UI.WebControls namespace and one of these controls is Sublayout. This was used to programmatically add a Sitecore sublayout to the current sublayout. This control inherits from Sitecore.Web.UI.WebControls.WebControl which contains all of the standard caching properties such as Cacheable, VaryByData, VaryByQueryString etc. Example usage of the Sublayout control:
In Sitecore MVC, the equivalent of the Sublayout control is to use the Rendering method on the Sitecore.Mvc.Helpers.SitecoreHelper within the view. For example:
One important thing to note is that when adding a rendering programmatically, the cache settings specified on the sublayout/rendering definition item in Sitecore are NOT picked up. To define cache settings on the Rendering method, you must use a method overload to specify the caching behaviour on the rendering. There is no intuitive overload where you can pass in values for Cacheable or VaryByData as with the WebControl. To add caching to the example above, an anonymous type needs to be defined, for example:
There is no IntelliSense when defining this and so it is hard to remember the property names without decompiling the Sitecore code or to look back at another project to see how you achieved this previously. The following code provides a method which accepts a strongly typed class to define the caching properties. It also provides the ability to cache a rendering by TimeSpan which could come in useful and isn't exposed as part of the standard Sitecore caching functionality.
This method is then used in a view such as:
If the extension method does not show up, you will need to ensure you have the namespace imported where it is defined. Adding the namespace to the web.config within the views directory will ensure it is available for all views, for example: