Posts
16
Comments
101
Trackbacks
18
Thursday, April 06, 2006
Custom Server Controls in 2.0

Ahh the joys of learning new tech. :)

In 2.0, if you have a custom server control in your app_code directory, it must have a namespace, and the register directive in a page that uses that control should look like this:

<%@ register namespace="TestWebControls" tagprefix="testControl" %>

<%@ register namespace="TestWebControls" tagprefix="testControl" %>

And this would be the code in your App_Code folder:

namespace TestWebControls
{
  [
ParseChildren(false)]
  [
PersistChildren(true)]
  [
ToolboxData("<{0}:TestControl runat=\"server\"")]
  [
AspNetHostingPermission(System.Security.Permissions.SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
[
AspNetHostingPermission(System.Security.Permissions.SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  public class TestServerControl : System.Web.UI.WebControls.WebControl
  {
    public override void RenderBeginTag(HtmlTextWriter writer)
    {
      this.AddAttributesToRender(writer);
      writer.RenderBeginTag(
"div");
    }
    public override void RenderEndTag(HtmlTextWriter writer)
    {
      writer.RenderEndTag();
    }
  }
}

Then in your markup, you would have:

<testControl:TestServerControl cssclass="Foo" id="foo1" runat="server">
   inside
testControl:TestServerControl>

the "TestServerControl" name must match the name of the class of your custom server control (which I overlooked...whoops). You can also register the control in your web.config for ease of use in multiple pages:

<system.web>
   <
pages>
      <
controls>
         <add namespace="TestWebControls" tagPrefix="testControl" />
      controls>
   pages>
system.web>

Since this control is only going to be used in this app, I don't need to put it in a separate dll. But if you do put it in a separate dll, all you need to add is the "assembly" attribute when registering your controls. Note that you can't add the control to your toolbox unless it's compiled into a separate dll.

posted @ Thursday, April 06, 2006 8:29 AM | Feedback (0)
News