LogoASPAlliance: Articles, reviews, and samples for .NET Developers
Passing Server-Side Values to Client-Side Script
by Peter Johnson
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 114825/ 82

Passing server-side variable values to client-side code is a rather common need for applications that have a client-side script that is at all complex, such as some client-side validation or data manipulation on the client side before posting back changes to the server.

Recently on the lists, someone asked how to pass a value from web.config to a JavaScript/JScript function.  One way to do it that I have seen quite often is to write all the script from the server, including the server-side value, such as in Listing 1.

Listing 1: How not to write client-side script – MyPage.aspx.vb

Dim sb As StringBuilder = New StringBuilder()
sb.Append("<script type=""text/javascript"" language=""javascript"">" & vbcrlf)
sb.Append("  var myVar =" & MyVariable & ";  //use a server-side statement to pull" & vbcrlf)
sb.Append("  function doSomething(){      //do something with myVar" & vbcrlf)
sb.Append("  }" & vbcrlf)
sb.Append("</script>" & vbcrlf)
Me.Page.ClientScript.RegisterClientScriptBlock(GetType(),"doSomething", sb.ToString())

This gets the job done, but I have found it to be a nightmare to code and no fun to maintain.  An approach I greatly prefer is to put as much as possible of the JavaScript in a separate .js file, so RegisterClientScript only sends down whatever variables that script needs.

Reasons to use a separate .js file

·         Readability/maintainability - Just looking at the code in Listing 1, we see it has many variables appending and escaping.  Sure, the .js function and the server-side value being written is all in one place, but it is also unreadable (not a winning tradeoff in my book).  Plus, if the .js function you are writing (creatively titled doSomething in Listing 1) is of any size or complexity, that code could quickly get much, much worse.  However, I concede that this reason is largely preference; the other reasons below are more objective ones.

·         Caching - A separate .js file that never changes can be cached on the client, increasing load time and saving bandwidth.

·         Processing time - There is no need for all that code to be on the server when it is just static text you are sending down to the client.  Instead, you are building a StringBuilder object, loading it up with a fair bit of text, converting it to a string and sending it down to the client dynamically.  Sending down a static file (and doing so less often if you are caching as I mention above) is easier on the web server, allowing you to process other code more quickly, handle more users at once, etc.

How to use a separate .js file

Using the example above, doSomething would be in the .js file, instead of being written by ASP.NET server-side code.   It would reference myVar; myVar itself would be sent down via RegisterClientScript.  There are three components to implement this—the .js file in Listing 2, the reference to the .js file in your page in Listing 3 for VB and Listing 4 for C#, and the server-side code to send JavaScript variables to the client, also in Listings 3 and 4.

Listing 2: MyPage.aspx.js

function doSomething()
  // do something with myVar

Listing 3: Reference to the .js file and code to send the value to the client - MyPage.aspx.vb

' Output the reference to the .js file
' Output the variable
Dim sb As StringBuilder = New StringBuilder()
sb.Append("<script type=""text/javascript"" language=""javascript"">" & vbCrLf)
sb.AppendFormat("var myVar = {0};" & vbCrLf, MyVariable)
sb.Append("</script>" & vbCrLf)
Me.Page.ClientScript.RegisterClientScriptBlock(GetType(), "doSomething", sb.ToString())

Listing 4: Reference to the .js file and code to send the value to the client - MyPage.aspx.cs

// Output the reference to the .js file
// Output the variable
StringBuilder sb = new StringBuilder();
sb.Append("<script type=\"text/javascript\" language=\"javascript\">\n");
sb.AppendFormat("var myVar = {0};\n", MyVariable);
Page.ClientScript.RegisterClientScriptBlock(GetType(), "doSomething", sb.ToString)

Note that the code in Listing 3 is similar to the code in Listing 1, except it writes a reference to the .js file instead of writing the contents of the .js file (the doSomething function) directly.  Since the function is now in a separate .js file, the only client-side script the server needs to generate and send down to the client itself is the bare minimum—the myVar variable.

If your control or page that needs this client-side code is not in the web site, but in a separate class library, fellow author Mark Hines has written an article on .js files as embedded resources in class libraries.  This way, your .js file stays with your .NET code, making version changes and other maintenance simple as can be.


I have shown you a few approaches you can take to send server-side values to client-side script and the benefits of putting as much of your client-side code as possible in a separate .js file, instead of embedding it in your server-side VB or C# code.  Following this approach will make maintaining your applications easier and provide a better experience to your users.

Product Spotlight
Product Spotlight 

©Copyright 1998-2017  |  Page Processed at 2017-03-30 10:44:16 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search