Click here to Skip to main content
Click here to Skip to main content

Pass Variables From Server to JavaScript after JavaScript is Loaded.

, 5 Mar 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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. 

// 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).

<%@ 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)

Share

About the Author

Marcio_Coelho
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 PinstaffSmitha Vijayan5-Mar-13 4:22 
GeneralRe: Missing file PinmemberMarcio_Coelho5-Mar-13 4:30 
GeneralRe: Missing file PinmemberMarcio_Coelho5-Mar-13 4:38 
GeneralRe: Missing file PinmemberMarcio_Coelho5-Mar-13 4:44 
GeneralRe: Missing file PinstaffSmitha Vijayan5-Mar-13 4:58 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141220.1 | Last Updated 5 Mar 2013
Article Copyright 2013 by Marcio_Coelho
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid