asp.net中javascript与后台c#交互

2019-05-22 23:58:38于丽

后台代码(.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>