JavaScript gets the background C # variable and calls the background method

Source: Internet
Author: User

Http://www.educity.cn/develop/495493.html

Sometimes it is necessary to get the value of the background variable in JavaScript, to judge the JavaScript execution logic, or to call the C # backend method to get the data, we can use the <%=%> expression is easy to implement, <%=%> mainly is to bind the expression , and evaluates the value of an 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>

JS get C # backend method, variable and session

See http://www.cnblogs.com/starxp/articles/1711650.html

JavaScript gets the background C # variable and calls the background method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.