Passing Server-Side Values to Client-Side Script
page 1 of 1
Published: 26 May 2006
Unedited - Community Contributed
Abstract
In this article Peter describes best practices for taking server-side values (whether from a database, web.config or a calculated value) and sending them to the client to be used by JavaScript.
by Peter Johnson
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 113458/ 109

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 AspAdvice.com 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
Me.Page.ClientScript.RegisterClientScriptInclude("MyPage.aspx.js""~/MyDir/MyPage.aspx.js")
 
' 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
Page.ClientScript.RegisterClientScriptInclude("MyPage.aspx.js""~/MyDir/MyPage.aspx.js");
 
// Output the variable
StringBuilder sb = new StringBuilder();
 
sb.Append("<script type=\"text/javascript\" language=\"javascript\">\n");
sb.AppendFormat("var myVar = {0};\n", MyVariable);
sb.Append("</script>\n");
 
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.

Conclusion

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.



User Comments

Title: Passing Server side Variables to Javascript   
Name: Kingsley Bainn
Date: 2011-04-01 1:08:01 PM
Comment:
I have a page that I am trying to retrieve an asp.net radio button's text to a session variable and subsequently to a javascript. If the user clicks a radio button amongst four radion buttons, I then use the radio button's checkedchanged event to set the session variable. Below is the sample code:

protected void Q2OptionARadioButton_CheckedChanged(object sender, EventArgs e)
{
if (Q2OptionARadioButton.Checked)
this.Session["QuestionTwoAnswer"] = Q2OptionARadioButton.Text.Trim();
}

protected void Q2OptionBRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (Q2OptionBRadioButton.Checked)
this.Session["QuestionTwoAnswer"] = Q2OptionBRadioButton.Text.Trim();
}

protected void Q2OptionCRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (Q2OptionCRadioButton.Checked)
this.Session["QuestionTwoAnswer"] = Q2OptionCRadioButton.Text.Trim();
}

protected void Q2OptionDRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (Q2OptionDRadioButton.Checked)
this.Session["QuestionTwoAnswer"] = Q2OptionDRadioButton.Text.Trim();
}

Unfortunately, the session variable comes without any value. What am I missing? I desperately need help!!!
Title: BC30182: Type expected.   
Name: Dolphus Pereira
Date: 2011-03-30 3:43:54 AM
Comment:
I tried the above given code.
I get the following error with the parenthesis in "GetType()" is empty.
BC30182: Type expected.

I looked for GetType() on google and found that the word "String" has to be in the parenthesis.

It doesn't give an error now, but doesn't work either.

Please help.
Title: WebDev   
Name: James Brown
Date: 2011-02-09 9:52:51 AM
Comment:
Is there anyway to fire javascript from serverside code from within a C# web application?

I have a button on my web page that when clicked runs some server side code from the codebehind. Just before the end of this server side code block I want to fire a javascript function (and pass it a variable) which is located in a js file.

Is it possible to implement this somehow? I am new to javascript. I am using the Google Maps API so I cant escape it.

Many Thanks
Title: what is proper diff b/w client&server side   
Name: amandeep
Date: 2010-12-09 9:27:31 PM
Comment:
i cant understand the proper diff b/w this plz clearly understand
Title: Passing a parameter to the javascript   
Name: Karun
Date: 2010-10-18 5:14:11 AM
Comment:
Not bad.
Title: eXtendcode   
Name: Alok Kumar
Date: 2010-02-26 4:56:35 AM
Comment:
It is nice article. really helped
Title: C# server to client object sending   
Name: Pasan Indeewara
Date: 2009-09-27 1:23:53 AM
Comment:
I was looking for , how to transfer data from server o client using a simple object, the obstacle i was in was serializing... anyway thx.
Title: Server side variable access   
Name: rahul
Date: 2009-09-17 4:09:15 AM
Comment:
Thanks .

This is very helpful . please keep posting such a stuff.

Thanks
http://TechZed.com
Title: how can i run server side code   
Name: sunita
Date: 2009-08-07 8:24:29 AM
Comment:
server side code is normally run on the server as if we dont have IIS installed on the system
Title: How can I call client side function from server side   
Name: Ibrahim Khalili
Date: 2009-06-25 2:49:56 AM
Comment:
How can I call client side fucntion from server side and also pass the parameters list.
Title: Collection object   
Name: Tasnim
Date: 2009-06-04 7:24:40 PM
Comment:
hi,
Below should be the actual declaration in .js file.


collection = [
'popuplate',
'me',
'with',
'data'
];

and i want to pass it as a string where inhMessage is a hidden field
inhMessage.Value = "['popuplate','me','with','data'];"
and in js file it is like this :
collection = document.getElementById("inhMessage").value;
even though i alerted the value and the value im geting while alerting is correct, but collection doesnt seem to work as the value is not getting assigned properly.any idea why.do let me know asap.
Title: How to Fetch Javascript return value in C# Code Behind   
Name: Hardeep
Date: 2009-04-06 1:46:22 AM
Comment:
I want to fetch a value from javascript function to code-behind file in asp.net
Thanks in advance
Title: how to improve a php language   
Name: Anish Kumar
Date: 2008-10-27 1:53:48 AM
Comment:
plz tell me,that how to impove a php language and plz tell me that php language is right language to create a project or not if not then what is right plz tell me
Title: How can i call serverside function from client side   
Name: Nirav
Date: 2008-09-09 7:12:19 AM
Comment:
Hi
I want to call a function written in code-behind from javascript.please help me out.
Thanks in advance
Title: Pass array variable from vb code benind page to java script   
Name: Loganathan
Date: 2008-08-30 2:09:19 AM
Comment:
I want sample code, Pass array variable from VB.NET code behind page to java script
Title: how to in c#   
Name: steph
Date: 2008-01-16 7:48:15 AM
Comment:
how to in c#
Title: how about vb script instead of js?   
Name: medconn
Date: 2008-01-10 11:21:07 AM
Comment:
also don't you need to pass some parameter to GetType() method?
Title: Thankyou   
Name: Brett Anthony
Date: 2007-03-18 12:32:30 AM
Comment:
Just ggogled this, saved me many hours, your a legend dude!
Title: Thanks From KC   
Name: Tony The Tiger
Date: 2007-02-12 2:49:59 AM
Comment:
Thanks, this has helped me with sleepless nights in Kansas City. All of what was outlined here makes perfect logical sense when it comes to passing variables from the code behind to the JavaScript at startup.

Thanks for your help, Tony
Title: How can I send value from js 2 server?   
Name: behnamasadi@yahoo.com
Date: 2006-11-16 3:27:12 PM
Comment:
How can I send value from js 2 server?
supose that in in javascript we have var x_js_var=10;

after page posted

in c# X_csharp_var=x_js_var

plz mail me
Title: How to return value of a client function to a server?   
Name: Anita
Date: 2006-11-14 3:42:44 PM
Comment:
If I use,

if(!this.IsStartupScriptRegistered("Startup"))
this.RegisterStartupScript("Startup", scriptString);

and produce a window.confirm, how can I get the return value of what the user clicked.
Title: how to troubleshoot   
Name: Rinat Abastado
Date: 2006-10-24 5:55:42 PM
Comment:
Dear Scott,

Thank you for the informative article. I read it though several times and I am trying to follow the recommendations but so far unsuccessfully. I am trying to update a .js file with global variables (declared at the beginning of the file) with values computed on the server. I am using the RegisterClientScriptInclude and the RegisterClientScriptBlock methods as explained in your article but so far without success.

I am assuming that when I am using the RegisterClientScriptBlock after the RegisterClientScriptInclude what happens is that the variables are appended to the in-memory .js file? Is that correct? How can I see what is the file that the browser is sent from my page?

Thank you,
Rinat
Title: Passing Server-Side Values to Client-Side Script?   
Name: Dhaval Somaiya
Date: 2006-10-03 2:06:56 AM
Comment:
I want to know how can a javascript variable be used to fetch an recordset of an SQL query written in vbscript.
Title: how can i access a javascript object   
Name: chris
Date: 2006-09-18 12:29:36 PM
Comment:
how can i access a javascript object(Array) from code behind on a button click
Title: How to call client function from Server   
Name: Sam Komo
Date: 2006-07-08 10:27:11 PM
Comment:
How do I pass value from a textbox control or any asp.net control to javascript?
Title: How to use code-behind variable in javascript   
Name: AP
Date: 2006-06-14 4:15:35 PM
Comment:
Hi!

How to access code-behind variable(say a) in javascript(in HTML) and pass the same variable ( a ) as a querystring(in HTML) to another page(say Page2)? On Page2 , I want to access variable 'a' from code-behind..Is it possible??? Please reply soon.

Thanks and regards,

ap.
Title: Facing problem in passing string value more than 256 Characters   
Name: Vivek
Date: 2006-06-12 7:54:12 AM
Comment:
Hi,
Article is really useful.Can you pleasetell me how to pass large amount of data i.e. strings more than 256 characters or xml string from server side to javascript.

Also tell me is there any way to pass custom objects/entities from server side to javascript directly.
Youe help will be great.

Thanx in Advance
Vivek
Title: RE: How to call client function from Server?   
Name: Richard
Date: 2006-06-12 5:17:35 AM
Comment:
Hello P.E.LAM,

Well one way to this would be to use the following in .Net.

if(!this.IsStartupScriptRegistered("Startup"))
this.RegisterStartupScript("Startup", scriptString);

Otherwise you generally attach client side code say for example for a button click event by using the following.

btnExample.Attributes.Add("onClick", "doSomething");

Hope this helps.

Richard
Title: How to call client function from Server?   
Name: P.E.LAM
Date: 2006-06-10 6:07:17 AM
Comment:
ur article is interesting. Buy i had a question, how do u call a function in the client site from Server site? Thanks.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2017 ASPAlliance.com  |  Page Processed at 2017-04-28 9:51:06 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search