When ASP.NET controls are rendered their ids sometimes change, like if they are in a naming container. Button1
may actually have an id of ctl00_ContentMai
I don't think there's a single "best practice" for doing this. There's plenty of different pretty good practices. Here's ours:
Every control which has client-side functionality renders a script block inline, directly below the markup for the control:
control markup
Each control has an accompanying JS like:
var CustomControl = function(id) {
this.control = document.getElementByID(id);
this.init();
};
CustomControl.prototype.init = function() {
//do stuff to wire up relevant events
};
In the codebehind, we do something like:
class CustomControl : Control
override void Render(HtmlTextWriter writer)
{
writer.WriteBeginTag("span");
writer.WriteAttribute("id", this.ClientID);
writer.Write(HtmlTextWriter.TagRightChar);
//write control markup
writer.WriteEndTag("span");
writer.WriteBeginTag("script");
writer.WriteAttribute("type", "text/javascript");
writer.Write(HtmlTextWriter.TagRightChar);
writer.Write(
string.Format("new CustomControl('{0}');", this.ClientID)
);
writer.WriteEndTag("script");
}