Friday, 21 January 2011

The Substitution Control


I hold the Substitution Control in highest regard, since it has saved my professional life, more than once.

The Substitution Control should be used in an output-cached Page, in a section that you want to display dynamic content.

In a nutshell, used it to punch some holes in your cached web page.


Here is an example of usage:

You have a SharePoint Web Page, that is output-cached.

However, this page has on the top, a user control that displays a welcome phrase to the current user:


Your markup should be something like this (if you are in a Masterpage):

<body .....>
......

<usercontrol1:WelcomeUser ID="WelcomeUser1" runat="server" />
....
</body>

To display the correct current context user, despite the output cache, you'll need to use the Substitution Control.

The WelcomeUser Control, should be something like this:

<asp:Substitution id="Substitution1" methodname="GetCurrentUser" runat="server">
</asp:Substitution>

The methodname property is the name of the method that will return the information you'll need to render in the Substitution section.

This method must:
  • Be a static method
  • Accept a parameter of type HttpContext
  • Return a value of type String.

For this example, you'll have something like this in the code behind:

public static string GetCurrentUser(HttpContext context)
{
try
{
SPUser user = SPControl.GetContextWeb(context).CurrentUser;
StringBuilder builder = new StringBuilder();
builder.Append("<div class='cssClass1;'>");
builder.Append("<div class='cssClass2;'>");
builder.Append(string.Format("Welcome, {0}",user.Name));
builder.Append("</div>");
builder.Append("</div>");

return builder.ToString();
}
catch (Exception innerException)
{ //LOG ERROR
return string.Empty;
}
}



Importante note: This control will not work inside an Update Painel.

No comments:

Post a Comment