Click here to Skip to main content
15,886,873 members
Articles / Programming Languages / Javascript
Tip/Trick

Pass Variables From Server to JavaScript after JavaScript is Loaded.

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
5 Mar 2013CPOL1 min read 17.6K   5   5
This sample demonstrates how to pass data (variables) from code behind to JavaScript.

Introduction 

The sample demonstrates how to pass variables from a code behind to JavaScript after the page is loaded.

Also, it shows how to create hierarchical objects in JavaScript so you can start organizing the variables you get in the way that is more structured and that become more readable.

Using the code

Code is ready to use and only requires Visual Studio.

The code behind:

In the string format below, five variables are being passed in the signature of the JavaScript function Obj_SubObjInit. In this example, the variables are the value from the TextBox1.Text  and 4 integers such as 2,3,4,5. (it could be any code behind data per say)

The only fact on this call is that, the page is already loaded and the JavaScript of the page already loaded as well.

when the user clicks on the button1, then the variables are passed. 

It will be useful when you want JavaScript to work with some data from the code behind after the page is loaded. 

C#
// Pass the variables to javascript
protected void Button1_Click(object sender, EventArgs e)
{
  string script = string.Format("setTimeout('Obj_SubObjInit(\"{0}\",\"{1}\",
    \"{2}\",\"{3}\",\"{4}\");',5);", TextBox1.Text, 2, 3, 4, 5);         
  ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", script, true);
}

ASP.NET:

Here is the JavaScript area.

Here, I am showing how to created JavaScript variables within JavaScript variables just to get a sense of organization and structure. It is not part of the main reason for this tip. However, since the tip to pass variables is so straight forward,  when I got the variables in the JavaScript function, I am adding them in structured JavaScript variables, in a organized way (just for demonstration purpose).

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" 
  CodeBehind="Javascript.aspx.cs" Inherits="ImageResize.Javascript" %>

<%@ Register Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        //this function will be initialized from code behind and in this
        // examples 5 variables will be available in JavaScript from the code behind
        function Obj_SubObjInit(vA, vB, vC, vD, vE) {

            var jsContainer;
            var VariablesX;
            var VariablesY;

            //code below gets the two above variables and make them part of the first variable.
            jsContainer =
            {"VariablesX" : VariablesX
            ,"VariablesY": VariablesY
            }
                            
            //now fill in the second variable
            jsContainer.VariablesX =
		    { "Var1": vA
		    , "Var2": vB
		    };          

            //now fill in the third variable
            jsContainer.VariablesY =
		    { "Var3": vC
            , "Var4": vD
            , "Var5": vE
		    };

            //now read it. *** MAIN PURPOSE OF THIS IS TO ORGANIZE AS YOU 
            //        WANT IN OBJECTS FOR BETTER READABLITY AND STRUCTURE ***
            alert(jsContainer.VariablesX.Var1);
        }
      
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>   
   
        <asp:Button ID="Button1" runat="server" 
          Text="Initialize My JavaScript Variables" onclick="Button1_Click" />
        <br />
        <asp:TextBox ID="TextBox1" runat="server" Text="This is in code Behind"></asp:TextBox>
    </div>
    </form>
</body>
</html> 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Financial Institution
United States United States
Technology Developer with 15 years of experience in the IT industry, mostly spent with financial applications and financial business models. Played various roles such as leadership, management, system architect, database modeling and development, middle tier code and development, GUI, Java Script, C#, VB, SQL Server, Sybase Power Design, Red Gate, Scribe, Metastorm, Telerik, Infragistic, Aspose, Silverlight, Visual studio 2010 and others.

Comments and Discussions

 
GeneralMissing file Pin
Smitha Nishant5-Mar-13 3:22
protectorSmitha Nishant5-Mar-13 3:22 
GeneralRe: Missing file Pin
Marcio_Coelho5-Mar-13 3:30
Marcio_Coelho5-Mar-13 3:30 
GeneralRe: Missing file Pin
Marcio_Coelho5-Mar-13 3:38
Marcio_Coelho5-Mar-13 3:38 
GeneralRe: Missing file Pin
Marcio_Coelho5-Mar-13 3:44
Marcio_Coelho5-Mar-13 3:44 
GeneralRe: Missing file Pin
Smitha Nishant5-Mar-13 3:58
protectorSmitha Nishant5-Mar-13 3:58 
Thanks!
Are you an aspiring author? Read how to submit articles to CodeProject: Article Submission Guidelines[^]

Questions? Ask an editor here...

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.