Things that make you go hmm...
Posted 2007-05-28.
In the same vein as the C#/.NET gotchas page, my least favorite list of things ASP.NET.
Server Control Generated DOM Element IDs
2007-05-28
With any moderately complex web application page, you often need to hook into a DOM element's ID attribute. Let's say you have a server control that looks like this:
<asp:textbox id='textbox_id' runat='server' />
Because you're doing stuff with jQuery selectors like this:
$(function(){
var selected_element = $('#textbox_id');
// do your jQuery stuff
});
In ASP.NET 1.XX, as any sane person would expect, the ID and name attributes (HTML generated by the control) are the same as the server control itself:
<input name="textbox_id" type="text" id="textbox_id" />
In ASP.NET 2.0, as any sane person would NOT expect, the generated HTML spits out id and name attributes much DIFFERENT than the server control:
<input name="ctl00$ph01$textbox_id" type="text" id="ctl00_ph01_textbox_id" />
The ctl00 prefix is consistent, but the rest of the prefix depends on your code. Why make things overly complicated?!? With the ASP.NET 1.XX model you could completely separate your JavaScript code from the ASP.NET code because you knew exactly what the ID attribute of the DOM element is. But in 2.0 you have to inject the ID attribute dynamically into the JavaScript. The prefix isn't hard to figure out, but the million dollar question is whether you can really count on M$ to keep the prefix convention consistent. For me the answer is a no-brainer, an emphatic "NO".
So now you must access the Control.ClientID property, for example, to hook into the Page OnLoad event:
protected override void OnLoad(EventArgs e) {
// the beginning of your JavaScript code
my js_string = "blah blah blah";
// HTML id attribute spit out by server control
js_string += textbox_id.ClientID;
// append rest of JavaScript code and
// inject string into HEAD section of document
}
Instead of having your JavaScript completely separated (1.XX style) from your .NET code, only adding a pointer to the JavaScript source file:
protected override void OnLoad(EventArgs e) {
// the beginning of your JavaScript code
my js_src = "<script src='/JS_FILE.js' type='text/javascript'></script>";
// inject js_src into HEAD section of document
}
Don't get me wrong - 2.0 has major improvements and features I love over 1.XX, but this "feature" just doesn't make sense...