How to use javascript variables in C# and vise versa

 How to use javascript variables in C# and vise versa

 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.

 Example :

ASPX

<script type=”text/javascript”>

$(document).ready(function() {

var Cadebehindvalue = ‘<%=value %>’;

var imagePath = <%=strImagePath %>;

alertCadebehindvalue);

});

</script>

</head>

<body>

<form id=”form1″ runat=”server”>

 Codebehind

public string value;

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

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

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.

key     : A unique identifier for the script block.

script  : 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);

SCRIPT :

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>

  indside the body tag

<form id=”form1″ runat=”server”>

<div>

<asp:HiddenField ID=”hdfValue” runat=”server” />

 Codebehind

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s