Monday 30 January 2012

SharePoint Formatted String Control

I've come to the conclusion that a little known but widely used control, the FormattedString control in the Microsoft.SharePoint.WebControls namespace, is a very useful control. Any search through the Control Templates delivered with SharePoint shows how often this control is used when rendering output through SharePoint. It works in the same way a String.Format would in code, only it's something that can be added to an ASCX or ASPX asset.

Let's have a closer look.

In a publishing scenario, if you have some HTML into which you need to inject a value from the current page then you may be able to use the FormattedString control to create the HTML, as you might using String.Format. This can include HTML (i.e. "&gt;p&lt;" instead of "<p>") and any other server-side control output.

In a simple example, to do this you simply add in the usual "{0}" indexed tokens and then, as child controls, you add in the field values. Here's an example, after which I'll explain a little more:

<SharePointWebControls:FormattedString runat="server" 
FormatText="&lt;p&gt;{0}&lt;/p&gt;&lt;p&gt;{1}&lt;/p&gt;" 
EncodeMethod="NoEncode">
    <SharePointWebControls:FieldValue 
runat="server" FieldName="Title" />
    <SharePointWebControls:FieldValue runat="server" 
FieldName="Description" />
</SharePointWebControls:FormattedString>

The 2 child controls (FieldValue) render out the value of the 2 page field values as strings which are then used by the FormattedString control to replace the 2 tokens respectively. You could, as child controls, use any server control to output more complex examples should you wish, or your own custom controls. The render sequence always processes child controls first, so whatever the output is from the child control is used. You can have as many tokens as required. Another scenario might be to get the server-relative URL of the site, which you can do by using the SPUrl function in an ASP Literal control.

Going back to my example, the FieldValue control itself, is another little-documented control which I frequently use as it renders the value of a field without much or any of the surrounding HTML, which results in cleaner markup. Using it in the above context makes sense as we only want the actual values, not the additional HTML a control might output.

More information can be found here: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.formattedstring.aspx and for the FieldValue control, some limited information can be found here: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.fieldvalue.aspx.

No comments:

Post a Comment