技术开发 频道

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

 

在错误处理中有两个比较重要的属性和方法: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 事件中处理异常。是不是很简单?

 

 

0
相关文章