ASP.NET AJAX 客户端 访问 Web Service(2)

 

客户端访问PageMethod

  • 只能在aspx页面中定义
  • 只能是public static方法
  • 使用WebMethodAttribute标记
  • ScriptManager的EnablePageMethod设置为true
  • 通过pageMethods.MethodName进行访问
一个访问PageMethod的示例

创建一个页面,页面代码如下

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        
        <input type="button" value="Get Current Time" onclick="getCurrentTime()" />
        
        <script language="javascript" type="text/javascript">
            function getCurrentTime() {
                
                PageMethods.GetCurrentTime(getCurrentTimeSucceeded);
            }
            function getCurrentTimeSucceeded(result) {
                alert(result);
            }
        </script>
    </form>
</body>
</html>

后台代码中添加

 

[WebMethod]
    public static DateTime GetCurrentTime()
    {
        return DateTime.Now;
    }

主要,要引入using System.Web.Services命名空间

 

这样,我们就可以在点击按钮后访问PageMethod得到一个当前时间啦

 

错误处理

  • 调用时,可以提供一个接收错误的回调函数
  • 包括超时和服务器端抛出的异常
  • 超时只能设置在WebService级别
  • 由Sys.Net.WebServiceError提供

      一个错误处理的示例

创建一个WebService添加如下代码

[WebMethod]
    public int GetDivision(int a, int b)//这里我们会使用它抛出一个经典的除0错误
    {
        return a / b;
    }

    [WebMethod]
    public int Timeout()//调用这个方法是,我们会首先设置它等待2秒,造成一个超时
    {
        System.Threading.Thread.Sleep(5000);
        return 0;
    }

然后创建一个页面,调用这个WebService

<asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="~/Demo03/ErrorHandling.asmx" />
            </Services>
        </asp:ScriptManager>
        
        <input type="button" value="Get Division" onclick="getDivision(5,0)" />
        <input type="button" value="TimeOut" onclick="timeout()" />
        <script language="javascript" type="text/javascript">

            function getDivision(a, b) {
                ErrorHandling.GetDivision(a, b, null, failedCallback);
            }

            function timeout() {
                ErrorHandling.set_timeout(2000);
                ErrorHandling.Timeout(null, failedCallback);
            }

            function failedCallback(error) {
                var message = String.format("Timeout:{0}\n Message:{1}\n Exception Type:{2}\n StackTrace:{3}", error.get_timedOut(), error.get_message(), error.get_exceptionType(), error.get_stackTrace());
                alert(message);
            }
        </script>

这时,我们点击按钮,就可以看到一些错误信息了,实际应用中,我们可以利用这些信息,在页面上相应的做一些提示

 

复杂数据类型使用基础

首先,定义一个Employee类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
///Employee 的摘要说明
/// </summary>
public class Employee
{
    private string _firstname;
    private string _lastname;
    private string _title;

    public Employee(string firstname, string lastname, string title)
    {
        this._firstname = firstname;
        this._lastname = lastname;
        this._title = title;
    }
    public Employee() { }
    public string FirstName
    {
        get { return this._firstname; }
        set { this._firstname = value; }
    }
    public string LastName
    {
        set { this._lastname = value; }
        get { return this._lastname; }
    }
    public string Title
    {
        get { return this._title; }
    }

    public int Salary { get; set; }

    public string FullName
    {
        get
        {
            return this.FirstName + this.LastName;
        }
    }
    public static implicit operator string(Employee employee)
    {
        return employee.FullName;
    }
}

然后创建一个WebService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
///ComplexType 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 
[System.Web.Script.Services.ScriptService]
public class ComplexType : System.Web.Services.WebService
{

    [WebMethod]
    public Employee DoubleSalary(Employee employee)
    {
        employee.Salary *= 2;
        return employee;
    }

    [WebMethod]
    public List<int> Reverse(List<int> list)
    {
        list.Reverse();
        return list;
    }

    [WebMethod]
    public IDictionary<string, Employee> GetEmployee()
    {
        Dictionary<string, Employee> result = new Dictionary<string, Employee>();
        Employee emp1 = new Employee();
        emp1.FirstName = "bai";
        emp1.LastName = "yulong";
        emp1.Salary = 2000;
        result[emp1.FullName] = emp1;

        Employee emp2 = new Employee();
        emp2.FirstName = "xiao";
        emp2.LastName = "yaojian";
        emp2.Salary = 4000;
        result[emp2.FullName] = emp2;

        return result;
    }
    
}

然后创建一个页面,使用他们,首先在页面中添加ScriptManager,引入上面创建的WebService,添加如下代码

<input type="button" value="Double Salary" onclick="doubleSalary()" />
        <input type="button" value="Reverse" onclick="reerse([1,2,3,4,5])" />
        <input type="button" value="Get Employee" onclick="getEmploee()" />
        <script language="javascript" type="text/javascript">
            function doubleSalary() {
                var employee = new Object();
                employee.FirstName = "bai";
                employee.LastName = "yulong";
                employee.Salary = 1000;
                ComplexType.DoubleSalary(employee, doubleSalarySucceeded);
            }

            function doubleSalarySucceeded(result) {
                var message = String.format("FirstName:{0}\nLastName:{1} \nFullName:{2} \nSalary:{3}", result.FirstName, result.LastName, result.FullName, result.Salary);
                alert(message);
            }

            function reerse(array) {
                ComplexType.Reverse(array, function(result) { alert(result); });
            }

            function getEmploee() {
                ComplexType.GetEmployee(getEmployeeSucceeded);
            }

            function getEmployeeSucceeded(result) {
                for (var name in result) {
                    alert(name + ":" + result[name].Salary);
                }
            }
        </script> 

这时,我们点击"Double Salary"按钮,就可以调用WebService上的DoubleSalary方法,使工资翻倍啦

如果我们这时用HTTP Watch看的话,就可以看见我们发送的是一个JSON字符串,返回的同样是一个JSON字符串,但是他在前面使用__type指定了一个Employee类型

其他的两个方法,演示的就是实现了IList和IDictionary接口的类型的使用方式,这里使用一些工具,就可以很明显的看到他们在发送和接受数据中的方式

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值