Accessing ASP.NET Controls in JavaScript Code

Posted on 1 Comment

ASP.NET controls essentially translate to a bunch of HTML and JavaScript code when being rendered in the browser, because HTML and JS is all what a browser can understand. So does that mean you can access an ASP.NET control with ease through JavaScript? Yes and no. Really depends on the version of .NET installed on the server (hosting your ASP.NET website).

HTML controls/elements/tags are generally referred to by their IDs. In plain JS, we would do something like:

var name = document.getElementById('txtName').value;

In jQuery, that would translate to:

var name = $('#txtName').val();

That’s assuming that your page has a text box with the ID “˜txtName’. One would expect that ASP.NET controls can also be referred to by their IDs in JavaScript. But that’s not always true. Prior to .NET 3, a compiler-generated prefix used to get added to a control’s ID (while rendering it in browser), to form what’s called the control’s ClientID. An example of such a ClientID can be “ctl00$mainpage$txtName”. In short, if you have an ASP.NET 3.0 textbox control having an ID “˜txtName’, you can access it in JavaScript like:

var name = document.getElementById('txtName').value;

But obviously, that won’t work in case of ASP.NET 2.0, because the actually ID you want to refer to is “ctl00$mainpage$txtName”.

That is where the ASP.NET short tag notation comes into play. Regardless of whatever version of .NET is installed on your server, you can access an ASP.NET control in JS in the following way:

var name = document.getElementById('<%= txtName.ClientId %>').value;

Of course, you can directly do something like:

var name = <%= txtName.Text %>;

Well, all depends on your needs. This tip is just meant to get you started with the interoperability between ASP.NET and JavaScript. And remember, the ASP.NET short tag notation works the same way in case of HTML too.

Further Reading
You can even have ASP.NET methods return data to your JavaScript code. That can be done with a little-bit of AJAX and by declaring your ASP.NET methods as webmethods. This beautiful tutorial discusses how to do just that (in plain JS and in jQuery)

1 thought on “Accessing ASP.NET Controls in JavaScript Code

  1. on my web page – totally free for many my customers

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.