asp.net中javascript與後台c#互動_實用技巧

來源:互聯網
上載者:User

最近做一個小項目,網頁中嵌入google maps,輸入經緯度座標可以定位地圖位置並加註標記,點擊標記擷取遠端網路攝影機資料並在視頻視窗實現播放。在實際操作過程中,由於經緯度資料和視頻登入的使用者名稱密碼資料均要從後台資料庫中提取,而第三版的google maps api又是在javascript中實現的,因此不可避免的需要前端指令碼與後台進行互動。由於是在asp.net中實現,故問題演化成asp.net中javascript與後台c#如何進行互動。

C#代碼與javaScript函數的相互調用主要有四個方面:

1.如何在JavaScript訪問C#函數?

2.如何在JavaScript訪問C#變數?

3.如何在C#中訪問JavaScript的已有變數?

4.如何在C#中訪問JavaScript函數?

一、javaScript函數中執行C#代碼中的函數:
方法一:頁面和頁面類結合
1、函式宣告為public            

      後台代碼(把public改成protected也可以)

 public string ss()    {    return("a");    }

2、在html裡用<%=ss()%>可以調用//是C#中背景函數名稱

      前台指令碼

 <script language=javascript>    var a = "<%=ss()%>";//JavaScript中調用C#背景函數    alert(a);    </script> 

方法二: JavaScript非同步呼叫定義在ASP.Net頁面中的方法   
              1.將該方法聲明為公有(public);   
              2.將該方法聲明為類方法(C#中的static,VB.NET中的Shared),而不是執行個體方法;   
              3.將該方法添加【WebMethod】屬性  
              4.將頁面中ScriptManager控制項的EnablePageMethods屬性設定為true;   
              5.在用戶端使用如下JavaScript文法調用該頁面方法   
                PageMethods.[MethodName](param1,param2,...,callbackFunction);   
               6.為用戶端非同步呼叫指定回呼函數,在回呼函數中接受傳回值並進一步處理;  
               7.添加 using System.Web.Services; 

樣本:

前台JavaScript代碼

<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>無標題頁</title> <script type="text/javascript"> function JsCallCSharp(param1) {     PageMethods.sayhell(param1,onSayHelloSucceeded);//sayhell是後台標註了【webMethod】屬性的方法 param1是傳入該方法的參數,onSayHelloSucceeded是回呼函數主要是對後台返回的結果進一步處理 }   function onSayHelloSucceeded(result)//綁定的回呼函數  {  alert(result); }  </script></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">//ScriptManager控制項管理指令碼的,注意設定EnablePageMethods="true"此屬性 </asp:ScriptManager> <div>  <input type="button" onclick="JsCallCSharp('hello')" /> </div> </form></body></html>

後台代碼(.cs檔案)

using System;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.Web.Services;//添加web服務引用public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) {   } [WebMethod]//標示為web服務方法屬性 public static string sayhell(string say)//注意函數的修飾符,只能是靜態 {  return say; }}

方法三: JavaScript非同步呼叫定義在Web服務類中的方法

              1.添加一個web服務標示該服務為 允許使用 ASP.NET AJAX 從指令碼中調用此 Web 服務

                對應屬性為[System.Web.Script.Services.ScriptService]

              2.將該方法聲明public並將該方法標示為[webMethod]屬性方法  
              3.在頁面中ScriptManager控制項並添加web服務引用                

<Services><asp:ServiceReferencePath="~/WebService.asmx" /></Services>  

              4.在用戶端使用如下JavaScript文法調用web服務方法

                WebService.HelloWorld("helloWord",function(res)//Webservice是web服務頁面名稱

                HelloWord為web服務頁面類中的方  法,function為回調JavaScript函數主要是處理返回的結果
                {
               alert(res);
                  });  

樣本:

頁面代碼

<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>無標題頁</title> <script type="text/javascript"> function JsCallCSharp(param1) {     PageMethods.sayhell(param1,onSayHelloSucceeded); }   function onSayHelloSucceeded(result) {  alert(result); } //該方法為調用的函數 function JsCallWebService() {  WebService.HelloWorld("helloWord",function(res)//調用web服務  {  alert(res);  }); } </script></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" > <Services><asp:ServiceReference Path="~/WebService.asmx" /></Services>//注意要引用web服務 </asp:ScriptManager> <div>  <input type="button" onclick="JsCallCSharp('hello')" value="測試C#後台頁" />  <input type="button" onclick="JsCallWebService()" value="測試web後台類" /> </div> </form></body></html>

web服務後台代碼

using System;using System.Collections;using System.Linq;using System.Web;using System.Web.Services;using System.Web.Services.Protocols;using System.Xml.Linq;/// <summary>///WebService 的摘要說明/// </summary>[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]//若要允許使用 ASP.NET AJAX 從指令碼中調用此 Web 服務,請取消對下行的注釋。  [System.Web.Script.Services.ScriptService]//注意要添加該標示public class WebService : System.Web.Services.WebService { public WebService () {  //如果使用設計的組件,請取消注釋以下行   //InitializeComponent();  } [WebMethod]//方法要標示的屬性 public string HelloWorld(string result) {  return result; } }

二、JavaScript訪問C#變數
方法一:
  a、通過頁面上隱藏欄位訪問,可以在後台把c#變數值儲存到隱藏文本域當中。

  <input id="xx" type="hidden" runat="server">
  b、然後在前台javascript當中直接取隱藏文本域的值。
   document.getElementByIdx_x('xx').value

方法二:
  a、在伺服器端變數賦值後在頁面註冊指令碼
  Page.RegisterStartScript(" ","<script language='javascript'>var vary=" + value + "</script>");
  value是後台變數,然後javascript中可以直接存取vary值,它的值就是後台變數value的值,這種方式只不過是能過一種間接的方式來訪問c#變數。
三、C#中訪問JavaScript的已有變數
方法一:前台使用伺服器文本控制項隱藏欄位,將js變數值寫入其中;後台直接通過控制項id訪問和調用,即後台用Request["id"]來擷取值。

方法二:可以用cookie或session儲存變數值,後台直接使用
使用session以下是程式碼片段:

.cs if (Session["siteName"] == null)//判斷是否存在指定Key值的Session變數 Session["siteName"] = "";//如果不存在則建立Session變數 //給Session["siteName"]變數賦值 .aspx var siteName="<%=Session["siteName"] %>";

四、C#代碼執行JavaScript函數和調用JavaScript函數
方法一:C#中使用ScriptManager.RegisterStartupScript(this, this.GetType(), "edit", "CSharpCallJs('"+param1+"','"+param2+"')",

樣本:

指令碼函數

function CSharpCallJs(param1,param2)   {    alert(param1 + param2);   } 

頁面後台代碼

ScriptManager.RegisterStartupScript(this, this.GetType(), "edit", "CSharpCallJs('" + param1 + "','" + param2 + "');", true);//關鍵代碼調用頁面指令碼函數的代碼

方法二:使用隱藏欄位或者Literal控制項,在前台使用js指令碼把一些js函數控制的值寫進隱藏欄位或者Literal控制項,然後前台使用Hidden.Value或者Literal.Text讀取前台值。
以下是程式碼片段:

 .aspx   function GetTitleID(obj)   {   sTitleID=obj   if(sTitleID!=null)   document.getElementByIdx_x("HiddenField1").value=type+','+sTitleID;   else   document.getElementByIdx_x("HiddenField1").value=type+',0';   }   .cs   string hiddenValue = this.HiddenField1.Value;

方法三:Page.RegisterStartupScript("function","<script>你要調用的javascript函數名稱;</script>");

以上就是asp.net中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.