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.
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">
function Obj_SubObjInit(vA, vB, vC, vD, vE) {
var jsContainer;
var VariablesX;
var VariablesY;
jsContainer =
{"VariablesX" : VariablesX
,"VariablesY": VariablesY
}
jsContainer.VariablesX =
{ "Var1": vA
, "Var2": vB
};
jsContainer.VariablesY =
{ "Var3": vC
, "Var4": vD
, "Var5": vE
};
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>