使用ASP.Net 3.5 的Ajax与Web服务开发实例

     本文继续介绍使用ASP.NET3.5中的AJAX环境中如何从客户端JavaScript调用Web服务方法。编写本文的目的在于让大家深刻了解基于ASP.Net3.5的

Ajax和Web的服务,虽然例子比较简单,但是比较能说明问题。在这里我又介绍了命名空间System.Web.Script的方式确定客户端调用Web服务方法。

     在AJAX中调用Web服务方法可以提高Web用户的体验,微软在ASP.NET3.5中的AJAX加入了它的新功能,新的功能可以从客户端JavaScript调用Web

服务方法无刷新整个页面。AJAX技术使你能够调用服务器端的方法,没有post back。客户端脚本可以提出请求的Web方法,并可以通过数据作为输入参数

的方法和数据也可以从服务器发回给客户端浏览器。

      为了使你的应用程序调用的ASP.NET Web service使用客户端脚本,服务器异步通信层会自动生成的JavaScript代理类。代理类生成为每个Web服务的

一个<asp:ServiceReference>元素被列入<asp:ScriptManager>控制的页面。

<asp:ScriptManager runat="server" ID="scriptManagerId">
     
<Services>
            
<asp:ServiceReference  Path="WebService.asmx" />
     
</Services>
</asp:ScriptManager>

     这是下载的代理类的浏览器在网页加载时间,并提供了一个客户端对象,代理调用方法的Web服务。在调用相应的方法所产生的JavaScript的代理类。该代

理类打开通信与网络服务。这些请求通过的XMLHTTP对象的浏览器异步通讯。 

      如下图所示,详细规定了不同的层上的客户机和服务器方面通讯框架。

 

     <asp:ScriptReference>元素指定注册一个JavaScript文件,用来在网页中。只有在注册CallWebServiceMethod.js文件,您才可以在方法上进行调用,

调用Web服务方法的脚本是异步的。获得返回值或以确定何时返回的请求,您必须提供一个成功的回调函数。回调函数被调用时,请求已成功完成,并且它包含

的返回值(如果有的话)从Web方法调用。您也可以提供一个失败的回调函数来处理错误。此外,您还可以通过用户的背景资料,使用中的回调函数。

如下图,是WCF和Ajax调用Web service时序图。

     在上一篇文章(基于ASP.NET 3.5 Web Service 的JSON扩展应用)中已经讲过,JSON - JavaScript对象符号是默认序列化格式,使用它进行数据转换

之间客户端服务器请求。您可以禁用所有目前启用的协议像HTTP-GET、HTTP-POST,甚至的XML格式的SOAP中使用的早期形式的Web服务。以下设置在

Web.config文件同样也是这样使用。

<system.web>
    
<webServices>
        
<protocols>
          
<clear/>
        
</protocols>
      
</webServices>
</system.web>

      请求一个Web服务方法通过这些层面。你可以看到如何使用一种方法,要求在一个可用的代理对象和Web请求中,并由一个XMLHttp对象在客户端浏览器

端运行。在服务器端,你的要求是与往常一样是由一个HTTP处理程序,发出的XML/JSON序列化。

如下图所示,asp.net 3.5调用Ajax与Web服务的类关系图。

                                            

      在AJAX中使用Web服务方法包括两个步骤:第一步是,创建和定义Web服务。第二个步,是使用客户端脚本来从一个网页的服务通话方法。创建一个Web服务:

在System.Web.Scripts.Services命名空间,你可能会发现一个属性类“ScriptSrvice ”,这需要适用于Web服务类,使Web服务方法可以调用来自客户端的脚本。这

将使代理生成脚本来生成一个代理对象对应于Web服务类。

      同样,在相同的命名空间,可能会发现另一个属性类“ScriptMethod”,如果采用此属性为Web方法,你可以指定哪些HTTP动词是用来调用一个方法和响应形式。

此属性有三个参数描述如下:

      UseHttpGet :如果设置为true,将调用该方法使用HTTP GET命令。默认值为false 。
      ResponseFormat :指定是否反应将序列化的简JSON或XML 。默认值为JSON。
      XmlSerializeString :指定是否所有返回类型,包括字符串类型,是为XML序列化的值将被忽略XmlSerializeString连续的响应来系列化的JSON 。

      现在,创建新的Web使用ASP.NET Web Service模板在Microsoft Visual Studio 2008和修改Web服务类如下:

using System.Web.Script.Services;

namespace AjaxWebService
{
    [WebService(Namespace 
= "http://localhost:1382/AjaxWebService/")]
    [WebServiceBinding(ConformsTo 
= WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    
public class Service : System.Web.Services.WebService
    {
        
string myXmlData = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                <Book>
                    <Title>Programming ASP.NET 3.5, AJAX and Web Services</Title>
                </Book>
";
       
        
/// <summary>
        
/// This method uses JSON response formatting 
        
/// </summary>
        
/// <param name="months"></param>
        
/// <returns></returns>
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        [WebMethod]
        
public string getNextBackupDate(int months)
        {
            
return DateTime.Now.AddMonths(months).ToShortDateString();
        }
        
        
/// <summary>
        
/// This method uses XML response formatting
        
/// </summary>
        
/// <returns></returns>
        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
        [WebMethod]
        
public XmlDocument GetBookTitle()
        {
            XmlDocument xmlDoc 
= new XmlDocument();
            xmlDoc.LoadXml(myXmlData);
            
return xmlDoc;
        }
       
        
/// <summary>
        
/// This method uses HTTP-GET protocol to call it
        
/// </summary>
        
/// <returns></returns>
        [ScriptMethod(UseHttpGet = true)]
        [WebMethod]
        
public string HelloWorld()
        {
            
return "Hello, world";
        }
    }
}

 注:Web服务创建的ScriptService使用如上将不会被浏览器默认。您需要修改文件中的设置Web.config文件如下,以测试上述Web服务。

<webServices>
     
<protocols>
       
<add name="HttpGet"/> 
       
<add name="HttpPost"/>
    
</protocols>
</webServices>

      调用Web服务方法使用客户端脚本,Asp.Net Web服务方法可以说是从客户端脚本异步不回传,并没有刷新整个页面。只有其之间传输数据的服务器和客户端的浏览器。
目前,.NET 3.5框架支持Web服务和客户端的网页可以在相同的域(同一网站)。

      现在增加一个新的“Ajax激活Web页” ,以现有的Web服务项目并添加控件的网页中指定的标记如下,编写JavaScript函数调用Web服务和回调方法。调用Web服务方法

是通过使用代理类和参数列表,成功回调函数名,失败的回调函数,用户方面是通过额外的参数的要求调用。

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

<!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>AJAX Web Form</title>
    
<script type="text/javascript">
function CallNextDate() 
    {
        AjaxWebService.Service.getNextBackupDate(
1, OnSucceeded);
    }

    
function CallHelloWorld() 
    {
        AjaxWebService.Service.HelloWorld(OnSucceeded);
    }
   
function CallBookTitle() 
    {
        AjaxWebService.Service.GetBookTitle(OnSuccess, OnFail, 
"XmlDocument");
    }
    
    
// This is the callback function that processes the Web Service return value in JSON format.
    function OnSucceeded(result)
    {
        
var myresult = document.getElementById("Text1");
        myresult.value 
= result;
    }
    
   
// This is the callback function that processes the Web Service return value in XML format.
    function OnSuccess(result)
    {
        
var myresult = document.getElementById("Text1");
        myresult.value 
= "Title: " + result.documentElement.text;
    }
    
   
// This is the callback function that processes the Web Service return value in XML format.
    function OnFail(error)
    {
        
var myresult = document.getElementById("Text1");
        myresult.value 
= "Service Error: " + error.get_message();
    }
     </script>
  
    
<style type="text/css">
        #Text1
        {
            width: 375px;
        }
        #Button2
        {
            width: 140px;
        }
    
</style>
  
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
<asp:ScriptManager ID="ScriptManager1" runat="server">
        
<Services>
        
<asp:ServiceReference Path="~/Service.asmx"/>
        
</Services>
        
</asp:ScriptManager>
        
<br />
        Result:
&nbsp;&nbsp;         <input id="Text1" type="text" /><br />
        
<br />
        
<input id="Button1" type="button" value="Get Server Time" onclick="CallNextDate()" />&nbsp;&nbsp;
        
<input id="Button2" type="button" value="Say Hello World" onclick="CallHelloWorld()" />&nbsp;&nbsp;
        
<input id="Button3" type="button" value="Get Book Title" onclick="CallBookTitle()" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        
<br />
        
<br />
        
<br />
        
</div>
    
</form>
</body>
</html>

      在上面的标记,通知的路径属性如何在ServiceReference元素ScriptManager控制点到Web服务类。这使得Web服务方法被称为从脚本中的default.aspx页面。

内嵌功能CallNextDate , CallHelloWorld , CallBookTitle是用来调用的三个Web服务方法。 OnSuccess和OnFail方法是回调方法,得到执行的Web

服务的方法得到了执行。为了使客户端的Web页的正常工作,您需要添加以下设置的Web.config文件。

<runtime>
    
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      
<dependentAssembly>
        
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
        
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      
</dependentAssembly>
      
<dependentAssembly>
        
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
        
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      
</dependentAssembly>
    
</assemblyBinding>
  
</runtime>

      本文使用微软ASP.NET 3.5引用的System.Web.Extensions.dll等DLL,利用内置的ASP.NET3.5中的AJAX技术仅供学习人员参考。

 参考代码下载

posted @ 2009-03-08 13:47  ξ箫音ξ  阅读(6815)  评论(3编辑  收藏  举报