asp.net中javascript與后臺c#交互
最近做一個小項目,網(wǎng)頁中嵌入google maps,輸入經(jīng)緯度坐標(biāo)可以定位地圖位置并加注標(biāo)記,點擊標(biāo)記獲取遠端攝像頭數(shù)據(jù)并在視頻窗口實現(xiàn)播放。在實際操作過程中,由于經(jīng)緯度數(shù)據(jù)和視頻登錄的用戶名密碼數(shù)據(jù)均要從后臺數(shù)據(jù)庫中提取,而第三版的google maps api又是在javascript中實現(xiàn)的,因此不可避免的需要前端腳本與后臺進行交互。由于是在asp.net中實現(xiàn),故問題演化成asp.net中javascript與后臺c#如何進行交互。
C#代碼與javaScript函數(shù)的相互調(diào)用主要有四個方面:
1.如何在JavaScript訪問C#函數(shù)?
2.如何在JavaScript訪問C#變量?
3.如何在C#中訪問JavaScript的已有變量?
4.如何在C#中訪問JavaScript函數(shù)?
一、javaScript函數(shù)中執(zhí)行C#代碼中的函數(shù):
方法一:頁面和頁面類結(jié)合
1、函數(shù)聲明為public
后臺代碼(把public改成protected也可以)
public string ss() { return("a"); }
2、在html里用<%=ss()%>可以調(diào)用//是C#中后臺的函數(shù)名稱
前臺腳本
<script language=javascript> var a = "<%=ss()%>";//JavaScript中調(diào)用C#后臺的函數(shù) alert(a); </script>
方法二: JavaScript異步調(diào)用定義在ASP.Net頁面中的方法
1.將該方法聲明為公有(public);
2.將該方法聲明為類方法(C#中的static,VB.NET中的Shared),而不是實例方法;
3.將該方法添加【W(wǎng)ebMethod】屬性
4.將頁面中ScriptManager控件的EnablePageMethods屬性設(shè)置為true;
5.在客戶端使用如下JavaScript語法調(diào)用該頁面方法
PageMethods.[MethodName](param1,param2,...,callbackFunction);
6.為客戶端異步調(diào)用指定回調(diào)函數(shù),在回調(diào)函數(shù)中接受返回值并進一步處理;
7.添加 using System.Web.Services;
示例:
前臺JavaScript代碼
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>無標(biāo)題頁</title> <script type="text/javascript"> function JsCallCSharp(param1) { PageMethods.sayhell(param1,onSayHelloSucceeded);//sayhell是后臺標(biāo)注了【webMethod】屬性的方法 param1是傳入該方法的參數(shù),onSayHelloSucceeded是回調(diào)函數(shù)主要是對后臺返回的結(jié)果進一步處理 } function onSayHelloSucceeded(result)//綁定的回調(diào)函數(shù) { alert(result); } </script> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">//ScriptManager控件管理腳本的,注意設(shè)置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服務(wù)引用 public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod]//標(biāo)示為web服務(wù)方法屬性 public static string sayhell(string say)//注意函數(shù)的修飾符,只能是靜態(tài)的 { return say; } }
方法三: JavaScript異步調(diào)用定義在Web服務(wù)類中的方法
1.添加一個web服務(wù)標(biāo)示該服務(wù)為 允許使用 ASP.NET AJAX 從腳本中調(diào)用此 Web 服務(wù)
對應(yīng)屬性為[System.Web.Script.Services.ScriptService]
2.將該方法聲明public并將該方法標(biāo)示為[webMethod]屬性方法
3.在頁面中ScriptManager控件并添加web服務(wù)引用
<Services><asp:ServiceReferencePath="~/WebService.asmx" /></Services>
4.在客戶端使用如下JavaScript語法調(diào)用web服務(wù)方法
WebService.HelloWorld("helloWord",function(res)//Webservice是web服務(wù)頁面名稱
HelloWord為web服務(wù)頁面類中的方 法,function為回調(diào)JavaScript函數(shù)主要是處理返回的結(jié)果
{
alert(res);
});
示例:
頁面代碼
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>無標(biāo)題頁</title> <script type="text/javascript"> function JsCallCSharp(param1) { PageMethods.sayhell(param1,onSayHelloSucceeded); } function onSayHelloSucceeded(result) { alert(result); } //該方法為調(diào)用的函數(shù) function JsCallWebService() { WebService.HelloWorld("helloWord",function(res)//調(diào)用web服務(wù) { 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服務(wù) </asp:ScriptManager> <div> <input type="button" onclick="JsCallCSharp('hello')" value="測試C#后臺頁" /> <input type="button" onclick="JsCallWebService()" value="測試web后臺類" /> </div> </form> </body> </html>
web服務(wù)后臺代碼
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 從腳本中調(diào)用此 Web 服務(wù),請取消對下行的注釋。 [System.Web.Script.Services.ScriptService]//注意要添加該標(biāo)示 public class WebService : System.Web.Services.WebService { public WebService () { //如果使用設(shè)計的組件,請取消注釋以下行 //InitializeComponent(); } [WebMethod]//方法要標(biāo)示的屬性 public string HelloWorld(string result) { return result; } }
二、JavaScript訪問C#變量
方法一:
a、通過頁面上隱藏域訪問,可以在后臺把c#變量值保存到隱藏文本域當(dāng)中。
<input id="xx" type="hidden" runat="server">
b、然后在前臺javascript當(dāng)中直接取隱藏文本域的值。
document.getElementByIdx_x('xx').value
方法二:
a、在服務(wù)器端變量賦值后在頁面注冊腳本
Page.RegisterStartScript(" ","<script language='javascript'>var vary=" + value + "</script>");
value是后臺變量,然后javascript中可以直接訪問vary值,它的值就是后臺變量value的值,這種方式只不過是能過一種間接的方式來訪問c#變量。
三、C#中訪問JavaScript的已有變量
方法一:前臺使用服務(wù)器文本控件隱藏域,將js變量值寫入其中;后臺直接通過控件id訪問和調(diào)用,即后臺用Request["id"]來獲取值。
方法二:可以用cookie或session存儲變量值,后臺直接使用
使用session以下是代碼片段:
.cs if (Session["siteName"] == null)//判斷是否存在指定Key值的Session變量 Session["siteName"] = "";//如果不存在則創(chuàng)建Session變量 //給Session["siteName"]變量賦值 .aspx var siteName="<%=Session["siteName"] %>";
四、C#代碼執(zhí)行JavaScript函數(shù)和調(diào)用JavaScript函數(shù)
方法一:C#中使用ScriptManager.RegisterStartupScript(this, this.GetType(), "edit", "CSharpCallJs('"+param1+"','"+param2+"')",
示例:
腳本函數(shù)
function CSharpCallJs(param1,param2) { alert(param1 + param2); }
頁面后臺代碼
ScriptManager.RegisterStartupScript(this, this.GetType(), "edit", "CSharpCallJs('" + param1 + "','" + param2 + "');", true);//關(guān)鍵代碼調(diào)用頁面腳本函數(shù)的代碼
方法二:使用隱藏域或者Literal控件,在前臺使用js腳本把一些js函數(shù)控制的值寫進隱藏域或者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>你要調(diào)用的javascript函數(shù)名稱;</script>");
以上就是asp.net中javascript與后臺c#交互的方法,每一種情況都有對應(yīng)的解決方法,希望能夠幫助到大家。
相關(guān)文章
asp.net獲取SQL所有數(shù)據(jù)庫名、所有表名、所有字段名
asp.net獲取SQL所有數(shù)據(jù)庫名、所有表名、所有字段名...2007-03-03ASP.NET MVC使用jQuery Template實現(xiàn)批量更新
這篇文章介紹了ASP.NET MVC使用jQuery Template實現(xiàn)批量更新的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07.Net?Api?中使用Elasticsearch存儲文檔的方法
Elasticsearch 是一個分布式、高擴展、高實時的搜索與數(shù)據(jù)分析引擎,在C# 的環(huán)境中,有一個Es的官方拓展包Nest,可以讓我們方便快捷的使用上Es數(shù)據(jù)庫,本文重點給大家介紹.Net?Api?中使用Elasticsearch存儲文檔的方法,感興趣的朋友一起看看吧2022-01-01Asp.net mvc 權(quán)限過濾和單點登錄(禁止重復(fù)登錄)
這篇文章主要介紹了Asp.net mvc 權(quán)限過濾和單點登錄(禁止重復(fù)登錄)的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-12-12asp.net Urlrewriter在虛擬主機上的使用方法
在網(wǎng)上看到,很多朋友在asp.net中做urlrewrite,用的是HttpHandle Server.Transfer的方法。其實這種方法是錯誤的。2009-12-12