Saturday, June 28, 2008

ASP.NET Control Adapters

Control Adapters are used to change the HTML rendered by specific ASP.NET controls. You can use them to deliver different HTML to a specific browser. You can also find CSS friendly control adapters on the ASP.NET site at http://www.asp.net/CssAdapters/

To create a control adapter, create a class that extends the WebControlAdapter class and overrides the Render method. Then, register the control adapter with the control that you would like to render by creating a .browser file in the App_Browsers ASP.NET folder.

In this article, I'll walk you through an example of a control adapter.

Let's start off by writing the web adapter class to render a Label control by displaying text in italics instead of rendering it within a span tag. The code for this is the following:


namespace ReddyveLib
{
public class LakeAdapter : WebControlAdapter
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
Label lbl = this.Control as Label;
if (lbl != null)
{
writer.Write("{0}", lbl.Text);
}
else
{
base.Render(writer);
}
}
}
}


You can then create the App_Browsers folder and create a browser file containing the following XML:


<browsers>
<browser refID="Mozilla">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.Label" adapterType="ReddyveLib.LakeAdapter" />
</controlAdapters>
</browser>
</browsers>


Within the controlAdapters section, we've added an adapter tag that identified the control we want to change the rendering of in the controlType attribute and the adapter class that we want to use in the adapterType attribute.

You can now run the website with a page containing a label and watch the difference.

No comments: