Sometimes you need to get the value of the background variable in JavaScript to determine the JavaScript execution logic, or you need to call the C # backend method to get the data , we can use <%=% The > expression is easily implemented, and <%=%> mainly binds the expression and evaluates the value of the expression.
1.JavaScript gets the background variable. Declare a global variable in the background and set the Access property of the variable to protected or public, which you can use on the page.
Declare a variable of type protected or public in the background C # code:
1 public partial class WebForm1:System.Web.UI.Page
2 {
3 protected string str;
4 protected void Page_Load (object sender, EventArgs e)
5 {
6 str = "Hello";
7}
8}<br>
Gets the value of the variable in the foreground JS:
1 <script type= "Text/javascript" >
2 $ (document). Ready (function () {
3 Alert ("<%=str%>");
4});
5 </Script>
2. Call the background method in JavaScript. To declare a public type method in the background , the Access property of the method must be public so that it can be accessed at the foreground.
A method that declares a pubic type in the background :
public partial class WebForm1:System.Web.UI.Page
02 {
protected void Page_Load (object sender, EventArgs e)
04 {
05
06}
public string Getstr ()
08 {
Return "Hello World";
10}
11}
Call the background C # method in the foreground JS to get the value:
1 <script type= "Text/javascript" >
2 $ (document). Ready (function () {
3 Alert ("<%=getstr ()%>");
4});
5 </Script>
JavaScript gets background C # variables and back-end methods