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 Variables

Prologue

I had a chance recently to attempt combining ASP.Net code and JavaScript code... For a while, I thought that attempt might be the operative word. I did get it to work, and I learned some valuable things, such as, the difference between the asp:literal and the asp:label controls. I was trying to create a scrolling banner from some JavaScript code I got off the web. It would take a line of HTML and display it, then scroll that one off and replace it with another line of HTML. Problem was the HTML lines had to be hard coded in the JavaScript. I didn't want our users to have to be hard coding the information so I wanted to have the information pulled at load time and then displayed, in other words, I needed to have the ASP.Net create some JavaScript for me.

Problem

The problem was to dynamically create a way for ASP.Net to pull a list of items, iterate through them and put them into the page as JavaScript variables (x="yyy"). This is something that I had done a number of times in classic asp, but it proved just a little more tricky than I anticipated in ASP.Net.

Solution

For this exercise, I won't list all the scrolling banner code, I will just put in a couple snippets that will help us to generate JavaScript from ASP.Net. I wanted the option to be able to use the code on multiple pages so I created it as a user control. For simplicity's sake, I won't do that here.

Start by creating a new web form. Let's name it AspToJs.aspx. In our AspToJs.aspx, we'll need a little JavaScript section so that we can successfully run our JavaScript. Go to the source of your page and add a script section between your form tags. In our script section, we want to add an alert and have it display a variable 'myVar'. It should look like this:

<script language="javascript" type="text/javascript">
   alert(myVar)
</script>

If you run your page, you'll get an error, myVar is undefined. Now, here's where we get into the project. We want our ASP.Net code to create the variable. Originally I tried to use an ASP.Net code section (<@ @>) directly in the source, but it would always cause an error because the javascript and ASP.Net were fighting so I went to the method I'm about to show you instead. Add a ASP:Label just above the alert, in this we'll add our variable declaration as follows:

<asp:Label ID="lblVar" runat="server" Text="myVar='Hi there'" />

Run the page and see what happens. Again an error. Why? Check the source of your page when you run it and notice that the ASP:Label control adds a span to the code. This unfortunately creates a syntax error in the javascript. So what to do? Change the ASP:Label to an ASP:Literal as follows:

<asp:Literal ID="lblVar" runat="server" Text="myVar='Hi there'" />

Now run it. Viola, it works. I learned that the ASP:Literal control just adds the text without any span, the ASP:Label control actually creates a span in the code.

But it still isn't quite the way I'd like it to be. I want to read a file and put the contents into the variable. I won't go through the code to read the contents, but let's modify the code so that creates an array of strings and then we get alerted for each one (which simulates what I wanted to do). Change your javascript section as follows:

var myVar=new Array() //notice, this line is new...
<asp:Literal ID="lblVar" runat="server" />
for (i=0;i<3;i++)
   {alert(myVar[i])}

We setup our code to iterate through an array and alert on each item, and we'll use our ASP:Literal to populate the array. Now let's build the code that will feed the ASP:Literal control. Open our code behind and create a new function to process the array items. Create a GenerateArrayItems function as follows:

Public Function GenerateArrayItems() As String
   Dim sb As New StringBuilder
   sb.Append("myVar[0]='First Item'" & vbCrLf)
   sb.Append("myVar[1]='Second Item'" & vbCrLf)
   sb.Append("myVar[2]='Third Item'" & vbCrLf)
   Return sb.ToString()
End Function

We create the array item, and assigned it a string value. Then we append the 'Carriage Return Line Feed' character to it, this will push the javascript code to the next line in our source code so it compiles ok. Ok, now let's add some code to the page_load to send our array items to our ASP:Literal control, add the following to the page_load event:

lblVar.Text = GenerateArrayItems()

Now run your page and they you go, you've generated javascript variables via ASP.Net. Now let's take it one step further. Let's say this page was a user control instead. Let's also say that in the user control, we could add a property that we could define in our Html code (as an attribute to our user control). Now let's say that we wanted to specify how many of the items get displayed as alerts. I won't go through creating the user control and the attributes and stuff, but we'll simulate the effect here. In addition, I found that you can put the code to populate the ASP:Literal control into the ASP:Literal control's load event (as opposed to the page_load event) so we'll do that for novelty's sake here. In your javascript, modify it so it looks like this:

var iNumToShow = <asp:Literal ID="lblNum" runat="Server" />
var myVar=new Array()
<asp:Literal ID="lblVar" runat="server" />
for (i=0;i<iNumToShow;i++) //<- - -Notice the change here
   {alert(myVar[i])}

Now we'll add the code to populate the lblNum ASP:Literal. In the code behind, add the following line to the lblNum_load event:

lblNum.Text = "1"

Now run your page and see how it works. Simple.

Epilogue

For me, this was a huge time saver. I was able to reuse some javascript code I got off the Internet (copy and paste inheritance we used to call it) and then make it so that our non-programmers could create a file and drop it into a folder and have it processed into the page. I actually created the whole thing as a user control and added properties to the control so we could manipulate parts of the javascript via the properties by using attributes in the HTML like so:

<uc3:ScrollingBanner ID="ScrollingBanner1" runat="server"
    PauseBetweenAdvertsInSeconds="10" TextAlign="center"  />

This way I could pass in my cssClass and other things, but not have to put them into the actual VB code just the HTML code. This example is setting how long to display one ad before scrolling to another and how to align the text of advert (they're all text only).

Posted: Friday, January 05, 2007 9:47 AM by Yougotiger
Filed under: ,

Comments

MAXMAN said:

Good ! thank the author.
# August 14, 2007 7:53 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

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