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,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。