Home/.Net/How to use javascript variables in C# and vise versa

How to use javascript variables in C# and vise versa

Passing values from server to client side (code-behind to .aspx) for some manipulation using javascript and passing values from script to code behind are one of the most recurring tasks while developing the application. This scenario can be achieved in many ways. In this post we are going to see some techniques to achieve this.

1. Passing values from C# Code Behind to JavaScript.

You can use <%=variable%> to get value from aspx.cs. Variable must be public in aspx.cs file. For example, you can use: var date=”<%=DateTime.Now%>”; to get the server time.

Code behind :

public string value;

protected void Page_Load(object sender, EventArgs e)
{
value = “From Code-Behind”;
}

ASPX Code : Now, we going to display this variable Variable Cadebehindvalue into html page using javascript:

<script type=”text/javascript”>
$(document).ready(function() {
var Cadebehindvalue = ‘<%=value %>’;
var imagePath = <%=strImagePath %>;
alert(Cadebehindvalue);
});
</script>
</head>
<body>
<form id=”form1″ runat=”server”></form>
</body>

2. Passing parameter from C# Code Behind to javascript.

Using RegisterStartupScript we can write a JavaScript function in code behind and call it from code-behind or from HTML. Look at the code below for reference.

Syntax: RegisterStartupScript(Control, Type, String, String, Boolean)

Explanation :

Control : The control that is registering the client script block.
Type : The type of the client script block. This parameter is usually specified by using the typeof operator (C#) or the GetType operator (Visual Basic) to retrieve the type of the control that is registering the script.
Boolean : true to enclose the script block with <script> and </script> tags; otherwise, false.

CodeBehind :

String EmployeeID =”Aadharsh”;

ScriptManager.RegisterStartupScript(this, this.GetType(), “TestKey”, “TableTest(‘” + this.EmployeeID + “‘);”, true);

Java Script in aspx :

function TableTest(EMPID)
{
var width = 600;
var height = 330;
var left = 500;
var top = 100;
window.open(‘welcome.aspx?EMPID=’ + EMPID,’_blank’,’toolbar=no,menubar=no,resizable=no,scrollbars=auto,status=no,location=no,
width=’ + width + ‘,height=’ + height + ‘,left=’ + left + ‘,top=’ + top);
}

3. Passing values from JavaScript to C# Code Behind.

ASPX: Using HiddenField

<script type=”text/javascript”>
$(document).ready(function() {
alert($(“#hdfValue”).val());
});
</script>

inside the body tag

<form id=”form1″ runat=”server”>
<div>
<asp:HiddenField ID=”hdfValue” runat=”server” />
</div>
</form>

Codebehind

protected void Page_Load(object sender, EventArgs e)
{
hdfValue.Value = “Chnaged Value in codebehind”;
}

Leave a Reply