Last post Aug 01, 2008 05:54 AM by email@example.com
Mar 25, 2008 09:16 PM|tstone|LINK
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:
That's it. Happy coding. (Tested with .NET framework 2.0)
/// Extended User Control that doesn't botch the HTML id attribute.
public partial class ExtendedUserControl : System.Web.UI.UserControl
public override void RenderControl(HtmlTextWriter writer)
// Render the control, placing the output in a string
StringWriter sw = new StringWriter(new System.Text.StringBuilder(),
HtmlTextWriter htw = new HtmlTextWriter(sw);
string chtml = sw.ToString();
// Match HTML id attributes that start with 'ctl'
Regex r = new Regex(@"\sid=""ctl[0-9]*_[A-Za-z][A-Za-z0-9]*""");
// Remove ASP.NET's adjusted id tag prefix
foreach (Match m in r.Matches(chtml))
//this.Response.Write(Regex.Replace(m.Value, @"ctl[A-Za-z0-9]*_", "") + "<br/>");
chtml = chtml.Replace(m.Value, Regex.Replace(m.Value, @"ctl[A-Za-z0-9]*_", ""));
Jul 10, 2008 10:40 AM|randomaccess|LINK
The main problem with this is that it will probably completely break AJAX.
The IDs are necessary for the framework to understand where things are in the control hierarchy,
The ctl00 originates from a server control for which you haven't specified an ID. It must be at the top of your control tree. Are you using a Master Page? You might have to specify IDs for your page placeholders. Then, you can target your CSS rule at #PageID_MyControl.
What bugs me about the IDs (and hence my search which found this post!) is the fact that they are added to so many elements unneccesarily. Unless really complex AJAX things are going on, I rarely need the IDs at all (in my application they're far too complex
and any form elements.
I'm looking into a way to use a modified HtmlTextWriter to eliminate unwanted IDs from being written out at all. I'll post if I have any luck.
Aug 01, 2008 05:54 AMfirstname.lastname@example.org|LINK
basically you can add attritubes from the code page of asp.net. use ClientID to add attritubes and call
TextBox1.Attributes.Add("onkeydown", "javafunction(" + TextBox1.ClientID + ")" );
asp.net will replace the id witt the newly created one