JavaScript和ASP.NET之间的传值

C#代码与javaScript函数的相互调用:

1.如何在JavaScript访问C#函数?

javaScript函数中执行C#代码中的函数:

方法一:页面和页面类相结合

1、函数声明为public , 后台代码(把public改成protected也可以)

 2、在html里用<%=ss()%>可以调用//是C#中后台的函数名称  

 1          C#后台的函数
 2     public string ss()
 3           {
 4                 return("a");
 5            }
 6 
 7            前台脚本
 8 
 9            <script language=javascript>
10             var a = "<%=ss()%>";//JavaScript中调用C#后台的函数
11             alert(a);
12            </script>     
View Code

方法二: 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;  

 1 前台JavaScript代码
 2 
 3 <html xmlns="http://www.w3.org/1999/xhtml">
 4 < head runat="server">
 5     <title>无标题页</title>
 6     <script type="text/javascript">
 7     function JsCallCSharp(param1)
 8     {            
 9           PageMethods.sayhell(param1,onSayHelloSucceeded);//sayhell是后台标注了【webMethod】属性的方法 param1是传入该方法的参数,onSayHelloSucceeded是回调函数主要是对后台返回的结果进一步处理
10     }        
11     function onSayHelloSucceeded(result)//绑定的回调函数 
12     { 
13         alert(result);
14     } 
15 
16     </script>
17 
18 </head>
19 < body>
20     <form id="form1" runat="server">
21     <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">//ScriptManager控件管理脚本的,
22 
23 注意设置EnablePageMethods="true"此属性
24     </asp:ScriptManager>
25     <div>
26         <input type="button" onclick="JsCallCSharp('hello')" />
27     </div>
28     </form>
29 < /body>
30 < /html>
31  后台代码(.cs文件)
32 using System;
33 using System.Configuration;
34 using System.Data;
35 using System.Linq;
36 using System.Web;
37 using System.Web.Security;
38 using System.Web.UI;
39 using System.Web.UI.HtmlControls;
40 using System.Web.UI.WebControls;
41 using System.Web.UI.WebControls.WebParts;
42 using System.Xml.Linq;
43 using System.Web.Services;//添加web服务引用
44 
45 public partial class _Default : System.Web.UI.Page
46 {
47     protected void Page_Load(object sender, EventArgs e)
48     {
49       
50 
51     }
52     [WebMethod]//标示为web服务方法属性
53     public static  string sayhell(string say)//注意函数的修饰符,只能是静态的
54     {
55         return say;
56     }
57 }
View Code

方法三: JavaScript异步调用定义在Web服务类中的方法

1.添加一个web服务标示该服务为 允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务

 对应属性为[System.Web.Script.Services.ScriptService]

2.将该方法声明public并将该方法标示为[webMethod]属性方法  
3.在页面中ScriptManager控件并添加web服务引用 <Services><asp:ServiceReference Path="~/WebService.asmx" /></Services>   
4.在客户端使用如下JavaScript语法调用web服务方法

 WebService.HelloWorld("helloWord",function(res)//Webservice是web服务页面名称 HelloWord为web服务页面类中的方法,function为回调JavaScript函数主要是处理返回的结果

 1 页面代码
 2 
 3 <html xmlns="http://www.w3.org/1999/xhtml">
 4 < head runat="server">
 5     <title>无标题页</title>
 6 
 7     <script type="text/javascript">
 8     function JsCallCSharp(param1)
 9     {            
10           PageMethods.sayhell(param1,onSayHelloSucceeded);
11     }        
12     function onSayHelloSucceeded(result)
13     { 
14         alert(result);
15     }  
16 
17 //该方法为调用的函数
18     function JsCallWebService()
19     {
20      WebService.HelloWorld("helloWord",function(res)//调用web服务
21      {
22          alert(res);
23      });
24     }
25     </script>
26 
27 </head>
28 < body>
29     <form id="form1" runat="server">
30     <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" >
31    <Services><asp:ServiceReference Path="~/WebService.asmx" /></Services>//注意要引用web服务
32     </asp:ScriptManager>
33     <div>
34         <input type="button" onclick="JsCallCSharp('hello')" value="测试C#后台页" />
35         <input type="button" onclick="JsCallWebService()" value="测试web后台类" />
36     </div>
37     </form>
38 < /body>
39 < /html>
40 
41 web服务后台代码
42 
43 using System;
44 using System.Collections;
45 using System.Linq;
46 using System.Web;
47 using System.Web.Services;
48 using System.Web.Services.Protocols;
49 using System.Xml.Linq;
50 
51 /// <summary>
52 ///WebService 的摘要说明
53 /// </summary>
54 [WebService(Namespace = "http://tempuri.org/")]
55 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
56 //若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 
57  [System.Web.Script.Services.ScriptService]//注意要添加该标示
58 public class WebService : System.Web.Services.WebService {
59 
60     public WebService () {
61 
62         //如果使用设计的组件,请取消注释以下行 
63         //InitializeComponent(); 
64     }
65 
66     [WebMethod]//方法要标示的属性
67     public string HelloWorld(string result) {
68         return result;
69     }
70 }
View Code
  1 方法一:使用<% %>
  2  <script  type="text/javascript">
  3           var s = "<%=ShowBehindInfo("chenliang")%>";  
  4           document.write(s);
  5  </script>
  6 cs后台代码:
  7 protected string ShowBehindInfo(string name)
  8 {
  9     return "姓名:" + name;
 10 }
 11 方法二:使用<% %>
 12   <script   type="text/javascript">
 13      document.write("<%ShowResult();%>");  
 14   </script>
 15 cs后台代码:
 16 protected void ShowResult()
 17 {
 18     Response.Write("我是陈全勇气");
 19 }
 20 方法三:
 21  <style>
 22         .btn
 23         {
 24             display:none;
 25         }
 26   </style>
 27 <asp:Button ID="Button1" runat="server"  CssClass="btn"  Text="Button" OnClick="Button1_Click" />
 28 <div  onclick="invokeCharp()">点击调用aspx.cs的代码</div>
 29 以下js代码将调用后台的cs代码
 30 function invokeCharp()
 31 {
 32     document.getElementById("Button1").click();
 33 }
 34 通过js调用的代码
 35  protected void Button1_Click(object sender, EventArgs e)
 36  {
 37     Response.Write("被js调用的代码");
 38  }
 39 方法四:
 40 <input type="hidden"   name="txtFunName">
 41 <input id="Button2" type="button" value="调用cs函数" onclick="return Button2_onclick()" />
 42 //将调用的信息存入隐藏控件中 在提交表单
 43 function Button2_onclick()
 44 {
 45     document.all.txtFunName.value="show";
 46     document.forms[0].submit();
 47 }
 48 //后台cs代码
 49 protected void Page_Load(object sender, EventArgs e)
 50 {
 51         string strFunName = Request.Form["txtFunName"] != null ? Request.Form["txtFunName"] : "";
 52         //根据传回来的值决定调用哪个函数
 53         switch (strFunName)
 54         {
 55             case "show":
 56                 enter(); //调用该函数
 57                 break;
 58             default:
 59                 //调用默认函数
 60                 break;
 61         }
 62 }
 63 方法五:
 64 使用__doPostBack();
 65 <input id="Button6" type="button" value="调用服务端的button" onclick="Button6_onclick()"  />
 66 <asp:Button ID="btn" runat="server"   Text="Button" OnClick="btn_Click" />  
 67 <asp:CheckBox ID="CheckBox1" AutoPostBack="true" runat="server" />
 68 function Button6_onclick()
 69 {
 70    var res = "chenliang";
 71    __doPostBack('btn','chenlinng');
 72 }
 73 //以上脚本将调用以下事件代码
 74 protected void btn_Click(object sender, EventArgs e)
 75 {
 76     string target = Request.Params["__EVENTTARGET"];
 77     string args = Request.Params["__EVENTARGUMENT"];
 78     Response.Write(target + "<Br>" + args);
 79 }
 80 __doPostBack解释:
 81 是一个纯粹并且是非常简单的javascript函数
 82 如以上代码,如果ASPX页面有包含asp:LinkButton或者带有AutoPostBack属性且其值为true的服务器控件时
 83 ASP.NET会自动为页面生成下面的脚本
 84 实际上调用__doPostBack函数
 85 也就是将触发回发的控件(第一个参数)及相关参数(第二个参数)付给两个页面的隐藏控件
 86 然后提交表单;
 87 <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
 88 <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
 89 function __doPostBack(eventTarget, eventArgument)
 90 {
 91    if (!theForm.onsubmit || (theForm.onsubmit() != false))
 92    {
 93       theForm.__EVENTTARGET.value = eventTarget;
 94       theForm.__EVENTARGUMENT.value = eventArgument;
 95       theForm.submit();
 96    }    
 97 }  
 98 而在后台事件代码中可以
 99 通过Request.Form[“__EVENTTARGET”]获取到触发页面PostBack的事件源(控件的ID)
100 但Button和ImageButton触发的PostBack无法通过这种方式获取到它们的ID
在javascript访问C#函数

 

2.如何在JavaScript访问C#变量?

方法一:1、通过页面上隐藏域访问<input id="xx" type="hidden" runat="server">

方法二:1、如后台定义了PUBLIC STRING N;前台js中引用该变量的格式为'<%=n%>'或"+<%=n%>+"

方法三:1、或者你可以在服务器端变量赋值后在页面注册一段脚本

             "<script language='javascript'>var temp=" + tmp + "</script>"

             tmp是后台变量,然后js中可以直接访问temp获得值。

 1 1.如何在javascript访问C#变量
 2 方法一:使用<%=%>
 3  <input id="Button3" type="button" value="js调用c#变量" onclick="return Button3_onclick()" />
 4 function Button3_onclick()
 5 {         
 6     alert('我的名字:''<%=name %>');
 7 }
 8 cs代码中的定义:protected string name = "chenlaing";
 9 方法二:使用Hidden隐藏控件
10   <input id="Hidden1" runat="server" type="hidden" />
11 在cs代码中给该隐藏控件赋值:  Hidden1.Value = "陈亮";
12 function Button3_onclick()
13 {         
14     alert(document.getElementById("Hidden1").value);
15 }
16 方法三:在cs代码中注册js脚本
17 string tmp = "陈全用";
18 ClientScript.RegisterClientScriptBlock(this.GetType(), null"<script language='javascript'>var temp='" + tmp + "'</script>");
19 function Button3_onclick()
20 {         
21      alert(temp);
22 }   
View Code

 

3.如何在C#中访问JavaScript的已有变量?

问题3 .如何在C#中访问JavaScript的已有变量?

方法一:1、前台使用服务器文本控件隐藏域,将js变量值写入其中;后台直接通过控件id访问和调用 (request["id"])

方法二:可以用cookie或session存储变量值,后台直接使用

4.如何在C#中访问JavaScript函数?

问题4 C#代码执行JavaScript函数和调用JavaScript函数

方法一: .尽量少用Response.Write(< script>< /script>);这种方法,它会影响CSS导致页面效果偏差

方法二:C#中使用ScriptManager.RegisterStartupScript(this, this.GetType(), "edit", "CSharpCallJs('"+param1+"','"+param2+"')",

 1 示例:
 2 
 3 脚本函数
 4 
 5 function CSharpCallJs(param1,param2)   
 6         {   
 7             alert(param1 + param2);   
 8         }  
 9 
10 页面后台代码
11 
12 ScriptManager.RegisterStartupScript(this, this.GetType(), "edit", "CSharpCallJs('" + param1 + "','" + param2 + "');", true);//关键代码调用页面脚本函数的代码
13 
14 方法三:C#中使用 Page.RegisterStartupScript("ggg","<script>CSharpCallJs“(”+param1+“,"+param2+“);"</script>");
15 
16 方法四:C#中使用Literal类(类似label类)
17 
18 示例代码
19 
20 private void Button2_Click(object sender, System.EventArgs e)
21 
22 {
23 
24 string str;
25 
26 str="<script language='javascript'>";
27 
28 str+="selectRange()";
29 
30 str+="</script>";
31 
32 //Literal1.Visible=true;
33 
34 Literal1.Text=str;
35 
36
View Code

 

posted @ 2020-07-18 10:03  江南-烟雨  阅读(2019)  评论(0编辑  收藏  举报