Wednesday 28 November 2012

Reference Asp.Net control in JavaScript

It can be a pain to reference an Asp.Net control in JavaScript.  I find myself inspecting rendered HTML and looking for the assigned ID (ClientID) of the control.  I decided the other day that I've had enough of doing that so I wrote this simple and small function...
public static void AddClientIDReference(System.Web.UI.Control Control)
{
    System.Web.UI.Page Page = HttpContext.Current.CurrentHandler as System.Web.UI.Page;
    System.Web.UI.ScriptManager.RegisterStartupScript(Page, typeof(System.Web.UI.Page),
        "ClientIDReference_" + Control.ID,
        "var " + Control.ID + " = \"" + Control.ClientID + "\"; ",
        true);
}
This can be called like this...
AddClientIDReference(txtMyTextBox);
This inserts a line of JavaScript that creates a global variable called txtMyTextBox, with a value of the textbox's ClientID.  You can then reference txtMyTextBox in JavaScript like this...
document.getElementById(txtMyTextBox);
or using jQuery...
$("#" + txtMyTextBox);
Like I said, simple and small :o)

No comments:

Post a Comment