Introduction

Have you ever written code to implement custom functionality, (text formatting, permission checks, etc.), to existing ASP.NET controls? You can achieve such customizations by implementing custom web controls, but wouldn't it be nice to apply extra attributes to existing ASP.NET controls to achieve the same result? This article covers a way you can use existing functionality in ASP.NET to extend existing web controls by applying your own custom HTML attributes.

A Quick Background

To understand this extended functionality, one must be familiar with the ASP.NET life-cycle, particularly the way a System.Web.UI.Page creates its child controls. If you look Page's object hierarchy, you can see that it directly inherits from the System.Web.UI.TemplateControl, which in terms inherits from the System.Web.UI.Control. The Control class defines the protected, and virtual, CreateChildControls method, a method used to notify server controls to create any contained child controls in preparation for posting back or rendering. To implement our own version of this method, we need to create our own class that inherits from System.Web.UI.Page.

Creating A Simple Custom Page

To implement a simple base ASP.NET page, define a new class that inherits from System.Web.UI.Page.

publicclass BasePage : System.Web.UI.Page { ... }

Next we need to override the CreateChildControls method to specify our own control creation logic.

protectedoverridevoid CreateChildControls() { ... }

Since all web and user controls must reside in a HTML form in order to work, we need to do two things:

Within CreateChildControls, iterate through all 'page' controls and find the control of type System.Web.UI.HtmlControls.HtmlForm

Iterate through the controls within the form control and select all controls of type System.Web.UI.WebControls.WebControl

The following code defines this discovery process:

///<summary>/// Overrides the common functionality for the creation
/// of controls within the page.
///</summary>protectedoverridevoid CreateChildControls()
{
// Find the form control in which all asp.net (or custom) controls
// must be hosted.
foreach (Control c inthis.Controls)
{
if (c is System.Web.UI.HtmlControls.HtmlForm)
{
ProcessForm(c as HtmlForm);
}
}
// Call the base implementation
base.CreateChildControls();
}
///<summary>/// Process each of the controls within the form
///</summary>///<paramname="form">The html form for the page</param>privatevoid ProcessForm(HtmlForm form)
{
// Find all the web controls, ie <asp:control_name />, and
// check process them.
//// You can also add logic here to check for user controls or
// custom user controls.
foreach (Control cc in form.Controls)
{
if (cc is WebControl)
{
// Once you find the a web control, process any
// custom attributes you have specified.
AttributeParser.ProcessControl(cc as WebControl);
}
}
}

Now that we have our base page and we've defined a discovery process, we can start the handling of our custom attributes with the help of some extra classes.

Stepping Through The Code

The main class for discovering custom HTML attributes is the AttributeParser class. This class contains a method called ProcessWebControl that simply iterates through all the previously defined attributes, represented by the AttributeType enumeration, and checks each web control's attributes for a match. If a match is found, the AttributeType is used in conjunction with the AttributeFactory class to get an instance of a class that implements the IAttribute interface. Using this class instance we then call the IAttribute.Apply method and pass the value of the attribute along with the control on which the attribute is defined in. This will allow the implementing class to perform any custom actions on the web control based on the value of the custom HTML attribute.

Two classes that implement the IAttribute interface are the PermissionAttribute class and the TextStyleAttribute class. The PermissionAttribute class is used to apply declarative security on the web control that contains the permission HTML attribute. In other words, if a TextBox controls defines the permission attribute in its HTML, then the TextBox will be enabled for the list of roles defined otherwise the control will be disabled.

Here's what the TextBox will look if the HttpContext.User is not part of Administrator role.

The TextStyleAttribute class is used to apply a custom look and feel to a TextBox web control. For this article I've implemented the phone style that formats your text as a phone number as you type it with the aid of JavaScript. To enable this custom style, you need to apply the textstyle custom HTML attribute to your text box.

<asp:textboxid="txtPhone"runat="server"textstyle="phone"/>

This TextBox will automatically add the '-' between the area code-prefix-postfix as you type in a number into the TextBox.

The TextStyleAttribute class is implemented a little bit different from the PermissionAttribute class in the sense that it uses the value of the custom attribute to further define custom actions within the custom HTML attribute. This allows you to implement different styles for the TextBox. For example, you can define a date textstyle that automatically formats the numbers entered as a simple date (mm/dd/yyyy). The TextStyleAttribute class is implemented as follows:

Conclusion

The two presented attribute implementations are intended to show you how easy it is to extend the current controls bundled with ASP.NET and to give you a head start for creating your own custom HTML attributes. If you currently have a custom ASP.NET framework adding this type of functionality will make your framework a bit more customizable.

Please feel free to leave any comments below.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

Share

About the Author

Javier is a consultant specializing in ASP.NET, system architecture, and training. He's also a MCSD .NET and a co-founder of the Iowa DotNET Users Group. Recently, Javier was awarded the Visual Developer ASP.NET MVP award from Microsoft.

On his blog you can find posts on ASP.NET, architecture, design patterns, XML and just recently, Indigo. Javier enjoys giving back to the community by speaking at user groups, local/regional .NET events, being active in forums and by writing articles for Code Project.

In his spare time, Javier enjoys spending time with his wife, newborn son, two golden retrievers and writing about himself in third person.

I loved the article and wanted to implement it on my web app.Solution worked for normal ASP.net pages.Worked on Masterpages, on its controls, if you change the Basepage to inherit from System.Web.UI.MasterPage

However it did not work on Content pages, as the content pages controls are contained within ContentPlaceHolders.The solution is:Inherit Basepage from System.Web.UI.Page (as normal)Inherit Content Page from Basepage (as normal)

I override Render but other methods should work too.Check for each control in me.forms.controlsTest for WebControls.ContentPlaceholderCast it to C and send to ProcessForm sub

In ProcessForm method, cycle through each Control in ContentPlaceHolder.controls...

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter) For Each c As Control In Me.Form.Controls If TypeOf c Is System.Web.UI.WebControls.ContentPlaceHolder Then ProcessForm(TryCast(c, ContentPlaceHolder)) End If Next MyBase.Render(writer) End Sub

Private Sub ProcessForm(ByVal CPH As ContentPlaceHolder) For Each cc As Control In CPH.Controls If TypeOf cc Is WebControl Then AttributeParser.ProcessControl(TryCast(cc, WebControl)) End If Next End Sub

This is so helpful. Imagine if you had a custom property that you wanted to add to every web control in your project. You would have to override every single type of control : ListBox, TextBox, Label, etc in order to be able to drag and drop the controls onto your forms. It's a dreadful proposition.

This allows me to, for example, also add on to to Third Party controls like Peter Blum's controls.