Accessing javascript variable from code behind and accessing code behind variable from javascript


/ Published in: JavaScript
Save to your folder(s)

Many times we face situation like when we need to access the code behind variables from javascript as well as accessing javascript variable from code behind.

I can remember a practical scenario in my previous project.

The requirement was to draw a organizational chart (What is Org chart?). On mouse hover on each node of the chart a window should get opened and all the information about the particular employee should be shown there without sny kind of postback(not even partial).

So here all you have to do is, you have to get all the required values from the server in to your code behind variable and then access them from your javascript code.

How to access code behind variable value from javascript?

Step 1: Define the variable in your code behind.

Step 2:Access the variable using the '' syntax.

public/protected string codeBehindVariable = "Hello World";// Step 1

var javascriptVar='';// Step 2

Point to be noted: Remember! The code behind variable that we are accessing from the javascript that must be a class level variable to a method/function lavel variable.

public partial class _Default : System.Web.UI.Page
{
private string codeBehindVariable = "Hello World";// class elvel variable not method level

protected void Page_Load(object sender, EventArgs e)

{

}

}

The variavle access modifier muct not be private or you will the the compilation error,

Error 2 '_Default.codeBehindVariable' is inaccessible due to its protection level

How can we access javascript variable value from the code behind?

Step 1: Put a HiddenField control in your html.

Step 2: Get the hiddenfield element id using document.GetElementByID() method and set the value property to any javascript variable.

Step 3: Access the hidden field variable from the code behind to access the value(the value of the javascript variable).


// Step 1




var valToPass='Joydeep Sen';

onload=function(){
document.getElementById ('').value=valToPass;// Step 2

}




label1.Text = hiddenfield1.Value;// Step 3

I think these approaches are quite simple and straightforward.


Copy this code and paste it in your HTML
  1. see comments

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.