技术开发 频道

用ASP.NET AJAX开发Web程序 — ScriptManager篇



【IT168 专稿】

源码下载

    摘要:该节主要介绍
ASP.NET AJAX Extensions服务器端控件 ScriptManagerScriptManagerProxy
   
   
ScriptManager控件包括在ASP.NET AJAX Extensions中,它提供处理页面上的所有ASP.NET AJAX组件(UpdatePanelUpdateProgress等)的支持。并且生成相关的客户端代理脚本以便能够在客户端脚本中访问Web Service。所有需要支持ASP.NET AJAXASP.NET页面上只能有一个ScriptManager控件。在ScriptManager控件中我们可以指定需要的脚本库,或者指定通过JS来调用的Web Service,以及调用AuthenticationServiceProfileService,还有页面错误处理等。

   
总而言之,ScriptManager控件是整个ASP.NET AJAX Extensions 的调度中心,没有该控件的存在其它控件是不能工作的。如果,您对asp.net 2.0熟悉的话,应该知道WebpartManager,它的功能和ScriptManager一样。

   
除了ScriptManager外,还有一个ScriptManagerProxy控件,这个控件只不过是当MasterPage中已经有ScriptManager时,在Content中只能使用ScriptManagerProxy了,其它功能和ScriptManager基本上一样。因此,本文将主要介绍ScriptManager的使用。


一、ScriptManager控件主要属性/方法

属性/方法

描述

AllowCustomError

config中的自定义错误配置区<customErrors>相联系,是否使用配置,默认值为true

AsyncPostBackErrorMessage

异步回传发生错误时的自定义提示错误信息,

AsyncPostBackTimeout

异步回传时超时限制,默认值为90,单位为秒

EnablePartialRendering

是否支持页面的局部更新,默认值为True,一般不需要修改

ScriptMode

指定ScriptManager发送到客户端的脚本的模式,有四种模式:AutoInheritDebugRelease,默认值为Inherit

ScriptPath

设置所有的脚本块的根目录,作为全局属性,包括自定义的脚本块或者引用第三方的脚本块。如果在Scripts中的<asp:ScriptReference/>标签中设置了Path属性,它将覆盖该属性。

OnAsyncPostBackError

异步回传发生异常时的服务端处理函数,在这里可以捕获一场信息并作相应的处理。

OnResolveScriptReference

指定ResolveScriptReference事件的服务器端处理函数,在该函数中可以修改某一条脚本的相关信息如路径、版本等。

 

下面是一个简单的ASP.NET AJAX示例,实现一个DropDownList 已选值,传递到一个LabelText属性中。该程序再也不用象原来一样,出现屏幕“闪烁“。我们可以看到浏览器的”后退“按纽是灰色的,说明该程序示例它是没有象传统的提交信息来实现交互的。

   
我们制作该示例程序很简单,只需要拖两个控件ScriptManagerUpdatePanl到页面中,然后在UpdatePanlContentTemplate中放入DropDownList,有两个选择项“hello,world“和“hello,ajax”(记得将DropDownListAutoPastBack设置为True),再放置一个Label
控件。这样我们就完成了简单的示例,在浏览器中浏览就可以看到效果了。

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"Namespace="System.Web.UI" TagPrefix="asp" %>
<script runat="server">
    void DropDownSelection_Change(Object sender, EventArgs e)
    {
        Label1.Text = DropDownList1.SelectedValue;
    }
</script>
<!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">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    </div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                &nbsp;<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownSelection_Change" AutoPostBack="True">
                    <asp:ListItem>hello,world</asp:ListItem>
                    <asp:ListItem> hello,ajax </asp:ListItem>
                </asp:DropDownList>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>
   
    是不是很简单,使用ASP.NET AJAX实现ajax效果就是这么简单。请在WEB.Config配置文件当中加入以下配置信息,否则程序将报“Sys未定义”错误:

<httpHandlers>
 <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>

下面我们将叙述如何来进行错误处理。

 

在错误处理中有两个比较重要的属性和方法:AsyncPostBackErrorMessage AsyncPostBackErrorMessage。在页面回传时如果发生了异,会触发AsyncPostBackError事件。而错误信息的处理主要依靠AsyncPostBackErrorMessage属性。AllowCustomErrors属性也可以用来处理错误信息,主要配合Web.config中的<customErrors>配置区。
   
   
下面看一个简单的错误处理例子,在AsyncPostBackError事件中捕获到异常信息并设置AsyncPostBackErrorMessage属性。

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

<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>

<script runat="server">

    void DropDownSelection_Change(Object sender, EventArgs e)
    {
        throw new Exception();
    }
    Protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
    {
        ScriptManager1.AsyncPostBackErrorMessage = "异常信息为:" + e.Exception.Message;
    }
</script>


<!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 id="Head1" runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
   
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackErrorMessage="failed msg" OnAsyncPostBackError=" ScriptManager1_AsyncPostBackError">
        </asp:ScriptManager>
   
    </div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                &nbsp;<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownSelection_Change" AutoPostBack="True">
                    <asp:ListItem>a</asp:ListItem>
                    <asp:ListItem>b</asp:ListItem>
                </asp:DropDownList>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

    上面的例子,我们将OnSelectedIndexChanged 事件处理中的方法,更改为抛出一个异常。然后,在OnAsyncPostBackError 事件中处理异常。是不是很简单?

 

 

 

Services属性是ScriptManager用来管理对WebService的调用,通过<asp:ServiceReference>标签可以在Services中注册一个WebService。在运行时,ScriptManager将为每一个ServiceReference对象生成一个客户端代理。<asp:ServiceReference>标签一个很重要的属性是Path,用来指定WebService的路径。在展示示例之前,必须要提示的是必须在程序配置文件web.config中增加下面配置,否则程序将运行不成功。

  <httpHandlers>
   <remove verb="*" path="*.asmx"/>
   <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
  </httpHandlers>

    我们将在以后的章节中介绍使用ASP.NET AJAX时,web.config的配置。

 
    下面是一个简单的webservice程序,到此之前都和以往开发web service是一样的。 但是,这个web service是从客户端脚本调用的。 也就是说,客户端脚本为了调用这个web service需要由一个代理。 我们可以给这个web service增加一个[ScriptService]属性来实现这个特性。 该属性在System.Script.Services命名空间内。 该命名空间在System.Web.Extensions程序集中。 [ScriptService]属性必须像下面这样应用到web service类中。

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

/// <summary>
/// service 的摘要说明
/// </summary>
[WebService(Namespace = "
http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class service : System.Web.Services.WebService {

    public service () {

        //如果使用设计的组件,请取消注释以下行
        //InitializeComponent();
    }
    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

 我们使用ASP.NET AJAX调用这个WebService。我们的代码最后的运行结果将弹出“Hello World”。下面是详细的代码:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CallWebService.aspx.cs" Inherits="CallWebService" %>
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>
<!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>
    <script type="text/javascript" language="JavaScript">
        function button_click()
        {
           requestSimpleService = service.HelloWorld(
            OnRequestComplete    //完成事件
            );
            return false;
        }
       
        function OnRequestComplete(result)
        {
            alert(result);
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="service.asmx" />
            </Services>
            </asp:ScriptManager>
        <input id="Button2" type="button" value="Call" onclick="return button_click()" /></div>
    </form>
</body>
</html>

 ScriptManagerProxy的使用和ScriptManager的使用方法基本相同,只不过是使用的地方不一样而已。我们将不再对它进行详细的描述。唯一要强调的是:ScriptManagerProxy的使用是当MasterPage已存在了ScriptManager,那么我们在Content中将使用ScriptManagerProxy。

总结

ScriptManager和ScriptManagerProxy的基本使用就介绍完成了,我们在该节主要介绍了ScriptManager的基本使用、错误处理及调用WebService的方法。在介绍它们的时候我们使用到了UpdatePanl控件。读者不用心急,我们在下一节中将会主要阐述UpdatePanel的用法。

0
相关文章