|
| Removing "ctl" prefix on HTML id attributes (code included) |
 |
Wed, 26 Mar 2008 01:16:02 +000 |
It's always bugged me that ASP.NET adds "ctlXXX_" to my HTML element
id attributes. It's particularly irritating because some elements I've defined
CSS styles specifically for them, and for ASP.NET to do so breaks that styling.
I put in some time this afternoon to write some code to eliminate that behavior.
This little snippet implements a derived class, ExtendedUserControl which
catches the RenderControl method and uses a Regular Expression to replace the
misshapen ID tag. Using the RegEx enables underscores ("_") to still
be used in id tag names, as it only grabs the ctlXXX_ instances.
How to use this:
Create a new class in your App_Code folder called
"ExtendedUserControl.cs"
Copy and paste the code from below into this new class.
Create a new "Web User Control"
Change the UserControl inheritance to ExtendedUserControl
For VB.NET: Change "Inherits System.Web.UI.UserControl" to
"Inherits ExtendedUserControl"
For C#.NET: Change " : System.Web.UI.UserControl" to " :
ExtendedUserControl"
That's it. Happy coding. (Tested with .NET framework 2.0)
1 using System;
2 using System.IO;
3 using System.Text.RegularExpressions;
4 using System.Data;
5 using System.Configuration;
6 using System.Web;
7 using System.Web.Security;
8 using System.Web.UI;
9 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 13 /// <summary>
14 /// Extended User Control that doesn't botch the HTML id attribute.
15 /// </summary>16 17 public partial class ExtendedUserControl :
System.Web.UI.UserControl
18 {
19 public override void RenderControl(HtmlTextWriter writer)
20 {
21 // Render the control, placing the output in a string22
StringWriter sw = new StringWriter(new System.Text.StringBuilder(),
23 System.Globalization.CultureInfo.InvariantCulture);
24 HtmlTextWriter htw = new HtmlTextWriter(sw);
25 base.RenderControl(htw);
26 string chtml = sw.ToString();
27 sw.Close();
28 29 // Match HTML id attributes that start with 'ctl'30 Regex r
= new
Regex(@"\sid=""ctl[0-9]*_[A-Za-z][A-Za-z0-9]*""");
31 32 // Remove ASP.NET's adjusted id tag prefix33 foreach (Match m in
r.Matches(chtml))
34 {
35 //this.Response.Write(Regex.Replace(m.Value, @"ctl[A-Za-z0-9]*_",
"") + "<br/>");36 chtml =
chtml.Replace(m.Value, Regex.Replace(m.Value, @"ctl[A-Za-z0-9]*_",
""));
37 }
38 39 this.Response.Write(chtml);
40 }
41 }
|
| Post Reply
|
|
|
|
|
|
|
|
|
|