Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Pass Variables From Server to JavaScript after JavaScript is Loaded.

0.00/5 (No votes)
5 Mar 2013CPOL1 min read 18.1K   77  
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)