从代码隐藏访问javascript变量和从javascript访问代码隐藏变量

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从代码隐藏访问javascript变量和从javascript访问代码隐藏变量相关的知识,希望对你有一定的参考价值。

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.
  1. see comments

以上是关于从代码隐藏访问javascript变量和从javascript访问代码隐藏变量的主要内容,如果未能解决你的问题,请参考以下文章

Java内存模型

内存模型

java内存模型

在 Javascript 中设置隐藏的输入值,然后在代码隐藏中访问它

Java内存模型

Java基础