Welcome to AspAdvice Sign in | Join | Help

.Net Discoveries

An attempt to pass along some answers I have discovered in my .Net coding.
Using ASP.Net to Create JavaScript Code


Several years ago, I created a post on this blog about using ASP.Net to create JavaScript variables. Times have changed, and I’ve found that sometimes I need to add more than just a couple variables to JavaScript to the page. Luckily, I found an easy way to add JavaScript code to your page ALL in the backend so that you don’t have to use those messy HTML/ASP.Net pieces.


When I started coding one of the most desired features of our Intranet, I ran into a slight issue with how long the page took to load. The page has over 100 data fields on it, and several of them will be displayed only if a certain option is selected from a DropDownList. While this isn’t hard to do, I was using a postback (with the UpdatePanel) to go back to the server and determine if the field needed shown and validation enabled for it.

The problem with this was that since the page was so hefty, it was a several second delay as it reprocessed the page. Users complained. I could use JavaScript to do the showing/enabling, however it’s typically a pain to identify the elements that are created by the ASP.Net code since it gives them lengthy ID’s at runtime. Thus the previous post about adding in variables to the JavaScript code so that the ClientID can be injected.

There is an easierbetter(?) way. You can create your entire JavaScript code block in your back-end code and then push it to the page. I found this also comes in quite handy if there are blocks of JS code that you may or may not want to be put to the page depending on options that are selected, thus possibly cutting down on page load time.

Adding a JavaScript code block isn’t all that difficult, there are several articles regarding in online, but I found it handy enough that I thought I’d post another.


Let’s get started. Open a new page in Visual Studio. We’ll create some working JavaScript on the page, and then convert it to code-behind. I’m going to make use of jQuery a little so I will be adding a script tag that references the jQuery framework to the page:

<script src="../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>

Add in HTML input element as follows:

<input type="text" id="txtTheOldBox" />
<input type="button" id="btnOld" onclick="countIt()" value="Count It" />

Let’s add a script section to your page with the following BLOCKED SCRIPT

<script type="text/javascript">
    function countIt()

Basically we’re just having the click event of the button alert us about the length of the text in the textbox, nothing overly special. Run and test it, and make sure it works.

Now, let’s add an ASP.Net textbox and make it a little more difficult. Add the following just below your input element:

<br /><asp:TextBox ID="txtTheBox" runat="server"  />
<asp:Button ID="btnNew" runat="server" OnClientClick="countIt()"
        Text="Count It" />

Now the question becomes, how do we identify our textbox in our JavaScript code since .Net will assign it a different id than the one we specify? In the previous post, I put embedded ASP.Net code into the JavaScript and when the page was parsed, the variables were entered. This gets a little problematic as it doesn’t always work cleanly. I’ve taken to putting this script into the code-behind and making it a little easier.

Let’s move our current JavaScript to our code-behind. First, let’s setup our Page_Load event so that it will call an AddJavaScript subroutine that will take care of adding our JavaScript. Add the following line to your Page_Load event handler:


and then start a subroutine for our Javascript as follows:

Private Sub AddJavaScript()
    Dim scriptBlock As New StringBuilder() 

    scriptBlock.Append("<script type=""text/javascript"">" & vbCrLf) 


    If (Not Page.ClientScript.IsStartupScriptRegistered("theScript")) Then
        Page.ClientScript.RegisterStartupScript(Me.GetType(), _
                   "theScript", scriptBlock.ToString())
    End If
End Sub

This is the basic start of our AddJavascript subroutine. We’ll create a StringBuilder object and then we’ll add our script block open and close to the StringBuilder. Finally, we’ll check and see if we have added this script to our page before. If we haven’t, then we’ll add the script to the page using the Page.ClientScript.RegisterStartupScript function. Notice that we pass in a name for the script (“theScript”) this is what we check against to make sure that we don’t add it twice and cause any problems.

Now, we’ll just want to start adding our JavaScript code between the two script tags. Add the following:

scriptBlock.Append("    function countIt()" & vbCrLf)
scriptBlock.Append("    {" & vbCrLf)
scriptBlock.Append("        alert($(‘#txtTheOldBox’).attr('value').length);" _
                                               & vbCrLf)
scriptBlock.Append("        _
         alert($(‘#" & txtTheBox.ClientID & "’).attr('value').length);" & vbCrLf)
scriptBlock.Append("    }" & vbCrLf)

We’ve basically copied and pasted our script code here and just added our StringBuilder’s append method to the beginning. I inserted tabs so that the code would be formatted nicely in the rendered code. Also, I added vbCrLf to the end of each line, this puts a Carriage Return/Line Feed at the end of each line. Be careful if you decided to leave these out as this will run all the script onto one line and you need to take care with writing your script to support that, little things can catch it up of you’re not careful.

In our second alert, we’ve taken out hard coding the name of the TextBox and we’ve used the object’s ClientID property to insert this into our rendered code. Now, even if we change what is around our textbox and the .Net code automatically changes the ClientID of the TextBox without our knowing, our code will still target correctly. Run your code and check it out.

Next, let’s tweak our code a little and use one function and pass it a parameter with the TextBox name rather than hard coding names (i.e. let’s make our function reusable). First, let’s modify our countIt function declaration to accept a parameter. Modify it as follows:

scriptBlock.Append("    function countIt(theTextBox)" & vbCrLf)

Comment out the two alert lines in your AddJavascript subroutine and add the following line in their place:

scriptBlock.Append("        alert($('#' + theTextBox).attr('value').length);" _
                          & vbCrLf)

In the front-side code, modify your input button’s onclick= parameter so that it reads:


This will call our modified countIt function and pass it it’s name. Now, how do we modify our asp:Button’s onClientClick parameter the same way? Take the onClientClick parameter out of our front-side code entirely, and add the following to your AddJavascript subroutine in the code-behind:

btnNew.OnClientClick = "countIt('" & txtTheBox.ClientID & "')"

Again, we’re making use of the TextBox’s ClientID property so that we don’t have to manually keep track of it on the front side. Run it again, and notice that we now only get one alert. Each button runs the function just on the textbox it is next to.


Combining JavaScript and ASP.Net code can be tricky, especially when attempting to target an ASP.Net control specifically with your script code. Putting the JavaScript in the code-behind makes it easier to accurately target the correct names.

Doing it this way isn’t without it’s pitfalls, it DOES make it harder to write JavaScript (although I tend to write it in the front-side code and then move it to the back once finished). But it’s been a successful strategy for me an I thought I’d pass it on.

Posted: Thursday, August 30, 2012 9:26 AM by Yougotiger
Filed under: ,


nancy graham looking for Javascript coding guidelines said:

Thanks for the explained part of coding.Your post is making clear so many confusions to me...:)
# September 1, 2012 3:49 AM
Leave a Comment





Enter the code you see below

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS