whihathac's Den

code is poetry

Tips n Tricks - Javascript and ASP.NET 2.0 - Part 1

Well I have learnt few things working with Javascript(JS) and AJAX in ASP.NET. I thought I'll put it here which can be used by others. The post concentrates majorly on Javascript.

1. Using ASP.NET Variables in Javascript

You can use ASP.NET variables which are global (public of course) as follows:

Suppose in C# file you have:

public string random= "0";

You can use the variable in JS (actually the ASP.NET page replaces the variable name on runtime) as follows:

<script type="text/javascript">
   function Foo()
      var var1 = '<%= random %>';

2. Simulating ASP.NET AJAX Applications

While simulating ASP.NET AJAX applications, we cannot really differentiate between the request being Async and if the page has posted back. Here’s a simple way to find it out – Just add a delay in the function which is run as an AJAX request. For Eg.


This will provide a delay of 10 seconds. So when the function freezes at this point for 10 secs, you can check whether other parts of the site are responsive. If they ain’t you know that its not an AJAX request.

3. Referring to ASP.NET controls in JavaScript

You can refer to the ASP.NET controls in Javascript code as follows:

var var2 = document.getElementById('<%= Label1.ClientID %>').getAttribute("InnerHtml");

In the above piece of code, Label1 is a Label and we use the InnerHtml attribute for extracting the Text Label.

4. Triming Strings in JS

Trimming in Javascript is kinda trivial in case you use RegEx. Here’s an example to do so -

strvar = strvar.replace(/^\s+|\s+$/g, '');


I’ll continue with few more tricks I have learnt in the next post. Thanks for the patience of reading the post :)


Bhavik Vora