ASP.NET Ajax学习笔记(二)客户端调用WebService

说明;本示例中用到的Employee类,上一篇文章中已写本文就省略掉了

客户端调用WebService过程:先实现WebService,再在客户端中调用WebService。


示例:

EmployeeService.asmx

<%@ WebService Language="C#" CodeBehind="~/App_Code/EmployeeService.cs" Class="EmployeeService" %>

EmployeeService.cs

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

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

    public EmployeeService () {

        //如果使用设计的组件,请取消注释以下行 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

    [WebMethod]
    public Employee GetEmployee(string firstName, string lastName, string title)
    {
        return new Employee(firstName+"Hello", lastName+"World", title);
    }
    
}

WebServiceAccess.Aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebServiceAccess.aspx.cs" Inherits="WebServiceAccess" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<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">
        <Services>
            <asp:ServiceReference Path="~/EmployeeService.asmx" />
        </Services>
    </asp:ScriptManager>

    <script type="text/javascript">
        function ShowEmployee(firstName, lastName, title) {
            EmployeeService.GetEmployee(firstName, lastName, title, onGetEmployeeSuccess);
        }
        function onGetEmployeeSuccess(employee) {
            alert(String.format("firstName:{0},lastName:{1},title:{2}", employee.FirstName, employee.LastName, employee.Title));
        }
    </script>
    <div>
        <input type="button" value="Bill Gates" onclick="ShowEmployee(‘Bill‘,‘Gates‘,‘Chair man‘)" />
        <input type="button" value="Steve Ballmer" onclick="ShowEmployee(‘Steve‘,‘Ballmer‘,‘CEO‘)" />
    </div>
    </form>
</body>
</html>





ASP.NET Ajax学习笔记(二)客户端调用WebService,布布扣,bubuko.com

ASP.NET Ajax学习笔记(二)客户端调用WebService

上一篇:ASP.NET Ajax学习笔记(一)异步通信层


下一篇:CSS:层叠样式表的冲突处理