JavaScript擷取後台C#變數以及調用後台方法

來源:互聯網
上載者:User

標籤:

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

  有時需要在JavaScript中擷取後台變數的值,來判斷JavaScript的執行邏輯,或者需要調用C#後台方法擷取資料,我們可以使用<%= %>運算式很容易地實現,<%= %>主要是對錶達式進行綁定,並計算運算式的值。

  1.JavaScript擷取後台變數。在後台聲明一個全域變數,並將變數的訪問屬性設定為protected或public,就可以在頁面使用了。

  在後台C#代碼中聲明一個protected或public類型的變數:

  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>

  在前台js中擷取變數的值:

  1 <script type="text/javascript">

  2    $(document).ready(function () {

  3        alert("<%=str %>");

  4    });

  5 </script>

  2.在JavaScript調用後台方法。在後台聲明一個public類型的方法,方法的訪問屬性必須為public,這樣才能在前台訪問。

  在後台聲明一個pubic類型的方法:

  01 public partial class WebForm1 : System.Web.UI.Page

  02 {

  03     protected void Page_Load(object sender, EventArgs e)

  04     {

  05

  06     }

  07     public string GetStr()

  08     {

  09         return "hello world";

  10     }

  11 }

  在前台js中調用後台C#方法擷取值:

  1 <script type="text/javascript">

  2     $(document).ready(function () {

  3         alert("<%=GetStr() %>");

  4     });

  5 </script>

 

 

 

 

 

 

 

js擷取c#後台方法,變數及session

參看 http://www.cnblogs.com/starxp/articles/1711650.html

JavaScript擷取後台C#變數以及調用後台方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.