How to set and read parameters on a static sublayout in Sitecore

In Sitecore there are two types of binding, static and dynamic. Static is when you use the Sublayout web control directly in your layout and specific the sublayout you want to use. Dynamic binding is when you use a Placeholder web control and set the sublayout that will appear in that placeholder in Sitecore via the placeholder key. When using dynamic binding you can give your sublayout a Parameters Template and set parameters in Sitecore, but how do you set parameters on a sublayout using static binding?

It’s actually very easy. First you want to set the parameters via code by setting the Parameters property on the Sublayout web control:

slMySublayout.Parameters = "Param1=true&Param2=hello world";

The property is just a string, but common practice sees you set the parameters as if it were a query string using an ampersand to separate the different parameters.

Next you want to read those parameters. You do that inside your Sublayout user control. When reading parameters with dynamic binding you read Attributes[“sc_parameters’], but here we’ve set the Parameters property on the Sublayout web control that is the container for the actual sublayout. We can read this like so:

var subLayout = (Sublayout)Parent;
if (subLayout != null)
    var parameters = Sitecore.Web.WebUtil.ParseUrlParameters(subLayout.Parameters);
    var param1 = parameters.Get("Param1");
    var param2 = parameters.Get("Param2");

Here we just get the Parent of the sublayout, which is the Sublayout web control container, and read the Parameters property. As I formatted it as a query string Sitecore has a handy ParseUrlParameters method which creates a NameValueCollection of the parameters. You can then get each parameters using the Get method.

Posted on by Joe in ASP.NET, C#, Sitecore

Add a Comment