Quantcast
Channel: asp.net – blog.boro2g.co.uk
Viewing all articles
Browse latest Browse all 6

Add ITemplate content to a controls markup

$
0
0

When building web controls, a common scenario is how to cascade control parameters to the control from the markup (or code-behind). Within Sitecore controls this is typically the Field you want to render.

<tc:SText runat="server" Field="Title" HideIfEmpty="true" />

This approach to programming controls works very well until the set of parameters becomes very long or the control doesnt need to know about each parameter. Consider embedding a flash movie, the number of parameters to code could be huge.

In the flash example, often the parameters aren’t needed by your c# code, instead they just to be rendered to the markup.

<pf:SFlash runat="server" Field="Flash Item" Width="384" Height="380">
    <ParametersTemplate>
        <param name="quality" value="high" />
        <param name="bgcolor" value="#006699" />
        ...
        <param name="salign" value="" />
        <param name="allowScriptAccess" value="sameDomain" />
        <param name="flashVars" value='dataURL=<%= FeedUrl() %>' />
    </ParametersTemplate>
</pf:SFlash>

One useful tip is that you can get information from your code behind into the template markup eg

<%= FeedUrl() %>

To build the control you need to add the following attribute:

[ParseChildren(true)]
public class SFlash : Control

And then the template you want to use:

[Browsable(false), DefaultValue(null), PersistenceMode(PersistenceMode.InnerProperty)]
public virtual ITemplate ParametersTemplate
{
    get { return _parametersTemplate; }
    set { _parametersTemplate = value; }
}

private ITemplate _parametersTemplate;

The content of the template can be extracted as a string with the following:

PlaceHolder placeholder = new PlaceHolder();

if (ParametersTemplate != null)
{
    ParametersTemplate.InstantiateIn(placeholder);
}   

StringWriter stringWriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(stringWriter);

placeholder.RenderControl(writer);

Note, based on the chosen implementation, you may not need the content of the template as a string. Instead you could simply instantiate to the control’s child controls


Viewing all articles
Browse latest Browse all 6

Trending Articles