PageRequestManager のイベントの処理

更新 : 2007 年 11 月

Microsoft AJAX Library の PageRequestManager クラスは、AJAX 対応の ASP.NET Web ページ上の ScriptManager サーバー コントロールおよび UpdatePanel サーバー コントロールと連係して、部分ページ更新を有効にします。PageRequestManager クラスは、ページ要素が非同期ポストバックを実行する場合にクライアントのプログラミングを簡略化するメソッド、プロパティ、およびイベントを公開します。たとえば、PageRequestManager クラスを使用すると、クライアント ページのライフ サイクル内のイベントを処理し、部分ページ更新に固有のカスタム イベント ハンドラを提供することができます。

クライアント スクリプトで PageRequestManager クラスを使用するには、Web ページに ScriptManager サーバー コントロールを含める必要があります。ScriptManager コントロールの EnablePartialRendering プロパティは true (既定値) に設定する必要があります。EnablePartialRendering を true に設定すると、PageRequestManager クラスを含むクライアント スクリプト ライブラリをページで使用できます。

PageRequestManager クラスのインスタンスの取得

ページごとに、PageRequestManager のインスタンスが 1 つ存在します。このクラスのインスタンスを作成することはありません。代わりに、次の例に示すように、getInstance メソッドを呼び出して現在のインスタンスへの参照を取得します。

Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);

PageRequestManager クラスの現在のインスタンスがある場合は、このクラスのすべてのメソッド、プロパティ、およびイベントにアクセスできます。たとえば、次の例に示すように、非同期ポストバックが実行中かどうかを示す isInAsyncPostBack プロパティを取得できます。

function InitializeRequest(sender, args)
{
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if (prm.get_isInAsyncPostBack() & args.get_postBackElement().id == 'CancelPostBack') {
        prm.abortPostBack();
    }    
}
function InitializeRequest(sender, args)
{
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if (prm.get_isInAsyncPostBack() & args.get_postBackElement().id == 'CancelPostBack') {
        prm.abortPostBack();
    }    
}

ScriptManager コントロールの EnablePartialRendering プロパティが false の場合、PageRequestManager のインスタンスが存在しないので、isInAsyncPostBack プロパティにアクセスできません。

クライアント ページのライフ サイクル イベント

ブラウザの通常のページ処理では、ページが最初に読み込まれるときに window.onload DOM イベントが発生します。同様に、ページが更新されたりユーザーがページから移動したりしたときには window.onunload DOM イベントが発生します。

しかし、これらのイベントは非同期ポストバック中には発生しません。PageRequestManager クラスでは、非同期ポストバックでこのような種類のイベントを管理するために、一連のイベントが公開されています。これらは window.load などの DOM イベントと似ていますが、非同期ポストバック中にも発生するという点が異なります。非同期ポストバックが発生するたびに、PageRequestManager クラスのすべてのページ イベントが発生し、割り当てられているすべてのイベント ハンドラが呼び出されます。

Bb398976.alert_note(ja-jp,VS.90).gifメモ :

同期ポストバックでは、pageLoaded イベントのみが発生します。

PageRequestManager クラスから発生したイベントを処理するクライアント スクリプトを記述できます。それぞれのイベント ハンドラに、異なるイベント引数オブジェクトが渡されます。PageRequestManager クラスのイベント、およびそれらに対応するイベント引数クラスを次の表に示します。この表のイベントの順序は、エラーが発生しない単一の非同期ポストバックでのイベントの順序です。

  • initializeRequest
    非同期ポストバックの要求が初期化される前に発生します。イベント データは、InitializeRequestEventArgs オブジェクトとしてハンドラに渡されます。このオブジェクトにより、ポストバックの原因となった要素と基の要求オブジェクトが使用できるようになります。

  • beginRequest
    非同期ポストバックがサーバーに送信される直前に発生します。イベント データは、BeginRequestEventArgs オブジェクトとしてハンドラに渡されます。このオブジェクトにより、ポストバックの原因となった要素と基の要求オブジェクトが使用できるようになります。

  • pageLoading
    最新の非同期ポストバックへの応答が受信された後、ページへの更新が完了する前に発生します。イベント データは、PageLoadingEventArgs オブジェクトとしてハンドラに渡されます。このオブジェクトにより、最新の非同期ポストバックの結果として削除および更新されるパネルに関する情報が使用できるようになります。

  • pageLoaded
    最新のポストバックが完了し、ページ領域が更新された後に発生します。イベント データは、PageLoadedEventArgs オブジェクトとしてハンドラに渡されます。このオブジェクトにより、作成または更新されたパネルに関する情報が使用できるようになります。同期ポストバックではパネルが作成されるだけですが、非同期ポストバックではパネルが作成および更新されます。

  • endRequest
    要求の処理が完了したときに発生します。イベント データは、EndRequestEventArgs オブジェクトとしてハンドラに渡されます。このオブジェクトにより、発生したエラーおよびエラーが処理されたかどうかに関する情報が使用できるようになります。応答オブジェクトも使用できるようになります。

非同期ポストバック時に ScriptManager コントロールの RegisterDataItem メソッドを使用して追加データを送信する場合は、PageLoadingEventArgsPageLoadedEventArgs、および EndRequestEventArgs の各オブジェクトからそのデータにアクセスできます。

イベントの順序は、シナリオによって異なります。前の表の順序は、単一の成功した非同期ポストバックの場合です。他にも次のようなシナリオが考えられます。

  • 最新のポストバックが優先される (既定の動作) 複数のポストバックが発生した場合。最新の非同期ポストバックに対するイベントのみが発生します。

  • 特定のポストバックが優先される (それが完了するまで後続のすべてのポストバックがキャンセルされる) 複数のポストバックが発生した場合。キャンセルされるポストバックに対する initializeRequest イベントのみが発生します。

  • 非同期ポストバックが停止された場合。ポストバックが停止されるタイミングによっては、一部のイベントが発生しない可能性があります。

  • ページの初期要求 (HTTP GET) またはページの更新が行われた場合。ページが最初に読み込まれるかまたはブラウザで更新されたときに、pageLoaded イベントのみが発生します。

非同期ポストバックの停止とキャンセル

一般的な 2 つのタスクとして、実行中の非同期ポストバックの停止と、新しいポストバックの開始前のキャンセルがあります。これらのタスクを実行するには、次の操作を行います。

  • 既存の非同期ポストバックを停止する場合は、PageRequestManager クラスの abortPostback メソッドを呼び出します。

  • 新しい非同期ポストバックをキャンセルする場合は、PageRequestManager クラスの initializeRequest イベントを処理し、cancel プロパティを true に設定します。

非同期ポストバックの停止

非同期ポストバックを停止する方法を次の例に示します。initializeRequest イベント ハンドラのスクリプトは、ユーザーがポストバックの停止を選択したかどうかをチェックします。選択した場合は、abortPostback メソッドを呼び出します。

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Collections.Generic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    Protected Sub NewsClick_Handler(ByVal sender As Object, ByVal e As EventArgs)
        System.Threading.Thread.Sleep(2000)
        HeadlineList.DataSource = GetHeadlines()
        HeadlineList.DataBind()        
    End Sub
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not (IsPostBack) Then
            HeadlineList.DataSource = GetHeadlines()
            HeadlineList.DataBind()
        End If
    End Sub
    ' Helper method to simulate news headline fetch.
    Private Function GetHeadlines() As SortedList
        Dim headlines As New SortedList()
        headlines.Add(1, "This is headline 1.")
        headlines.Add(2, "This is headline 2.")
        headlines.Add(3, "This is headline 3.")
        headlines.Add(4, "This is headline 4.")
        headlines.Add(5, "This is headline 5.")
        headlines.Add(6, "(Last updated on " & DateTime.Now.ToString() & ")")
        Return headlines
    End Function
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Canceling Postback Example</title>
    <style type="text/css">
    body {
        font-family: Tahoma;
    }
    #UpdatePanel1{
       width: 400px;
       height: 200px;
       border: solid 1px gray;
    }
    div.AlertStyle {
      font-size: smaller;
      background-color: #FFC080;
      width: 400px;
      height: 20px;
      visibility: hidden;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div >
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
        <asp:ScriptReference Path="CancelPostback.js" />
        </Scripts>
        </asp:ScriptManager>
        <asp:UpdatePanel  ID="UpdatePanel1" runat="Server" >
            <ContentTemplate>
                <asp:DataList ID="HeadlineList" runat="server">
                    <HeaderTemplate>
                    <strong>Headlines</strong>
                    </HeaderTemplate>
                    <ItemTemplate>
                         <%# Eval("Value") %>
                    </ItemTemplate>
                    <FooterTemplate>
                    </FooterTemplate>
                    <FooterStyle HorizontalAlign="right" />
                </asp:DataList>
                <p style="text-align:right">
                <asp:Button ID="RefreshButton" 
                            Text="Refresh" 
                            runat="server" 
                            OnClick="NewsClick_Handler" />
                </p>
                <div id="AlertDiv" class="AlertStyle">
                <span id="AlertMessage"></span> 
                &nbsp;&nbsp;&nbsp;&nbsp;
                <asp:LinkButton ID="CancelRefresh" runat="server">
                Cancel</asp:LinkButton>                      
            </ContentTemplate>
        </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Collections.Generic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void NewsClick_Handler(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(2000);
        HeadlineList.DataSource = GetHeadlines();
        HeadlineList.DataBind();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HeadlineList.DataSource = GetHeadlines();
            HeadlineList.DataBind();
        }
    }
    // Helper method to simulate news headline fetch.
    private SortedList GetHeadlines()
    {
        SortedList headlines = new SortedList();
        headlines.Add(1, "This is headline 1.");
        headlines.Add(2, "This is headline 2.");
        headlines.Add(3, "This is headline 3.");
        headlines.Add(4, "This is headline 4.");
        headlines.Add(5, "This is headline 5.");
        headlines.Add(6, "(Last updated on " + DateTime.Now.ToString() + ")");
        return headlines;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Canceling Postback Example</title>
    <style type="text/css">
    body {
        font-family: Tahoma;
    }
    #UpdatePanel1{
       width: 400px;
       height: 200px;
       border: solid 1px gray;
    }
    div.AlertStyle {
      font-size: smaller;
      background-color: #FFC080;
      width: 400px;
      height: 20px;
      visibility: hidden;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div >
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
        <asp:ScriptReference Path="CancelPostback.js" />
        </Scripts>
        </asp:ScriptManager>
        <asp:UpdatePanel  ID="UpdatePanel1" runat="Server" >
            <ContentTemplate>
                <asp:DataList ID="HeadlineList" runat="server">
                    <HeaderTemplate>
                    <strong>Headlines</strong>
                    </HeaderTemplate>
                    <ItemTemplate>
                         <%# Eval("Value") %>
                    </ItemTemplate>
                    <FooterTemplate>
                    </FooterTemplate>
                    <FooterStyle HorizontalAlign="right" />
                </asp:DataList>
                <p style="text-align:right">
                <asp:Button ID="RefreshButton" 
                            Text="Refresh" 
                            runat="server" 
                            OnClick="NewsClick_Handler" />
                </p>
                <div id="AlertDiv" class="AlertStyle">
                <span id="AlertMessage"></span> 
                &nbsp;&nbsp;&nbsp;&nbsp;
                <asp:LinkButton ID="CancelRefresh" runat="server">
                Cancel</asp:LinkButton>                      
            </ContentTemplate>
        </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

詳細については、「非同期ポストバックのキャンセル」を参照してください。

新しい非同期ポストバックのキャンセル

特定の非同期ポストバックを優先する方法を次の例に示します。これにより、現在の非同期ポストバックが完了するまで、後続のすべての非同期ポストバックがキャンセルされます(既定では、最新の非同期ポストバックが優先されます)。initializeRequest イベント ハンドラは、ページ上の優先される要素によって非同期ポストバックが開始されたかどうかをチェックします。そうである場合、InitializeRequestEventArgs オブジェクトの cancel プロパティを設定することにより、後続のすべてのポストバックがキャンセルされます。InitializeRequestEventArgs イベントは、cancel プロパティが定義された CancelEventArgs クラスを継承します。

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

<script runat="server">
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        System.Threading.Thread.Sleep(4000)
        Label1.Text = "Last update from server " & DateTime.Now.ToString()
    End Sub

    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
        System.Threading.Thread.Sleep(1000)
        Label2.Text = "Last update from server " & DateTime.Now.ToString()
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Postback Precedence Example</title>
    <style type="text/css">
    body {
        font-family: Tahoma;
    }
    #UpdatePanel1, #UpdatePanel2 {
      width: 400px;
      height: 100px;
      border: solid 1px gray;
    }
    div.MessageStyle {
      background-color: #FFC080;
      top: 95%;
      left: 1%;
      height: 20px;
      width: 600px;
      position: absolute;
      visibility: hidden;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Scripts>
            <asp:ScriptReference Path="PostBackPrecedence.js" />
            </Scripts>
            </asp:ScriptManager>
            <asp:UpdatePanel  ID="UpdatePanel1" UpdateMode="Conditional" runat="Server" >
                <ContentTemplate>
                <strong>UpdatePanel 1</strong><br />

                This postback takes precedence.<br />
                <asp:Label ID="Label1" runat="server">Panel initially rendered.</asp:Label><br />
                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />&nbsp;
                <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
                <ProgressTemplate>
                Panel1 updating...
                </ProgressTemplate>
                </asp:UpdateProgress>
                </ContentTemplate>
            </asp:UpdatePanel>
            <asp:UpdatePanel  ID="UpdatePanel2" UpdateMode="Conditional" runat="Server" >
                <ContentTemplate>
                <strong>UpdatePanel 2</strong><br />
                <asp:Label ID="Label2" runat="server">Panel initially rendered.</asp:Label><br />
                <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
                <asp:UpdateProgress ID="UpdateProgress2" runat="server" AssociatedUpdatePanelID="UpdatePanel2">
                <ProgressTemplate>
                Panel2 updating...
                </ProgressTemplate>
                </asp:UpdateProgress>
                </ContentTemplate>
            </asp:UpdatePanel>
           <div id="AlertDiv" class="MessageStyle">
           <span id="AlertMessage"></span>
           </div>
        </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(4000);
        Label1.Text = "Last update from server " + DateTime.Now.ToString();        
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(1000);
        Label2.Text = "Last update from server " + DateTime.Now.ToString();        
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Postback Precedence Example</title>
    <style type="text/css">
    body {
        font-family: Tahoma;
    }
    #UpdatePanel1, #UpdatePanel2 {
      width: 400px;
      height: 100px;
      border: solid 1px gray;
    }
    div.MessageStyle {
      background-color: #FFC080;
      top: 95%;
      left: 1%;
      height: 20px;
      width: 600px;
      position: absolute;
      visibility: hidden;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Scripts>
            <asp:ScriptReference Path="PostBackPrecedence.js" />
            </Scripts>
            </asp:ScriptManager>
            <asp:UpdatePanel  ID="UpdatePanel1" UpdateMode="Conditional" runat="Server" >
                <ContentTemplate>
                <strong>UpdatePanel 1</strong><br />

                This postback takes precedence.<br />
                <asp:Label ID="Label1" runat="server">Panel initially rendered.</asp:Label><br />
                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />&nbsp;
                <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
                <ProgressTemplate>
                Panel1 updating...
                </ProgressTemplate>
                </asp:UpdateProgress>
                </ContentTemplate>
            </asp:UpdatePanel>
            <asp:UpdatePanel  ID="UpdatePanel2" UpdateMode="Conditional" runat="Server" >
                <ContentTemplate>
                <strong>UpdatePanel 2</strong><br />
                <asp:Label ID="Label2" runat="server">Panel initially rendered.</asp:Label><br />
                <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
                <asp:UpdateProgress ID="UpdateProgress2" runat="server" AssociatedUpdatePanelID="UpdatePanel2">
                <ProgressTemplate>
                Panel2 updating...
                </ProgressTemplate>
                </asp:UpdateProgress>
                </ContentTemplate>
            </asp:UpdatePanel>
           <div id="AlertDiv" class="MessageStyle">
           <span id="AlertMessage"></span>
           </div>
        </div>
    </form>
</body>
</html>

詳細については、「特定の非同期ポストバックの優先的処理」を参照してください。

カスタム エラー メッセージの表示

非同期ポストバック中にエラーが発生したときにカスタム エラー メッセージを表示する方法を次の例に示します。ScriptManager コントロールの AsyncPostBackError イベントがサーバー コードで処理され、エラーに関する情報がブラウザに送信されて表示されます。

<%@ Page Language="VB" %>

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

<script runat="server">

    Protected Sub ErrorProcessClick_Handler(ByVal sender As Object, ByVal e As EventArgs)
        'This handler demonstrates an error condition. In this example
        ' the server error gets intercepted on the client and an alert is shown. 
        Dim exc As New ArgumentException()
        exc.Data("GUID") = Guid.NewGuid().ToString().Replace("-"," - ")
        Throw exc

    End Sub

    Protected Sub SuccessProcessClick_Handler(ByVal sender As Object, ByVal e As EventArgs)
        'This handler demonstrates no server side exception.
        UpdatePanelMessage.Text = "The asynchronous postback completed successfully."
    End Sub

    Protected Sub ScriptManager1_AsyncPostBackError(ByVal sender As Object, ByVal e As System.Web.UI.AsyncPostBackErrorEventArgs)
        If Not (e.Exception.Data("GUID") Is Nothing) Then
            ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message & _
                " When reporting this error use the following ID: " & _
                e.Exception.Data("GUID").ToString()
        Else
            ScriptManager1.AsyncPostBackErrorMessage = _
                "The server could not process the request."
        End If
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>PageRequestManager endRequestEventArgs Example</title>
    <style type="text/css">
    body {
        font-family: Tahoma;
    }
    #AlertDiv{
    left: 40%; top: 40%;
    position: absolute; width: 200px;
    padding: 12px; 
    border: #000000 1px solid;
    background-color: white; 
    text-align: left;
    visibility: hidden;
    z-index: 99;
    }
    #AlertButtons{
    position: absolute;
    right: 5%;
    bottom: 5%;
    }
    </style>
</head>
<body id="bodytag">
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" 
                               OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"
                               runat="server" />

            <script type="text/javascript" language="javascript">
                var divElem = 'AlertDiv';
                var messageElem = 'AlertMessage';
                var bodyTag = 'bodytag';
                Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
                function ToggleAlertDiv(visString)
                {
                     if (visString == 'hidden')
                     {
                         $get(bodyTag).style.backgroundColor = 'white';                         
                     }
                     else
                     {
                         $get(bodyTag).style.backgroundColor = 'gray';                         

                     }
                     var adiv = $get(divElem);
                     adiv.style.visibility = visString;

                }
                function ClearErrorState() {
                     $get(messageElem).innerHTML = '';
                     ToggleAlertDiv('hidden');

                }
                function EndRequestHandler(sender, args)
                {
                   if (args.get_error() != undefined)
                   {
                       var errorMessage = args.get_error().message;
                       args.set_errorHandled(true);
                       ToggleAlertDiv('visible');
                       $get(messageElem).innerHTML = errorMessage;
                   }
                }
            </script>
            <asp:UpdatePanel runat="Server" UpdateMode="Conditional" ID="UpdatePanel1">
                <ContentTemplate>
                    <asp:Panel ID="Panel1" runat="server" GroupingText="Update Panel">
                        <asp:Label ID="UpdatePanelMessage" runat="server" />
                        <br />
                        Last update:
                        <%= DateTime.Now.ToString() %>
                        .
                        <br />
                        <asp:Button runat="server" ID="Button1" Text="Submit Successful Async Postback"
                            OnClick="SuccessProcessClick_Handler" OnClientClick="ClearErrorState()" />
                        <asp:Button runat="server" ID="Button2" Text="Submit Async Postback With Error"
                            OnClick="ErrorProcessClick_Handler" OnClientClick="ClearErrorState()" />
                        <br />
                    </asp:Panel>
                </ContentTemplate>
            </asp:UpdatePanel>
            <div id="AlertDiv">
                <div id="AlertMessage">
                </div>
                <br />
                <div id="AlertButtons" >
                    <input id="OKButton" type="button" value="OK" 
                           runat="server" onclick="ClearErrorState()" />
                </div>
           </div>
        </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>

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

<script runat="server">

    protected void ErrorProcessClick_Handler(object sender, EventArgs e)
    {
        // This handler demonstrates an error condition. In this example
        // the server error gets intercepted on the client and an alert is shown.
        Exception exc = new ArgumentException();
        exc.Data["GUID"] = Guid.NewGuid().ToString().Replace("-"," - ");
        throw exc;
    }
    protected void SuccessProcessClick_Handler(object sender, EventArgs e)
    {
        // This handler demonstrates no server side exception.
        UpdatePanelMessage.Text = "The asynchronous postback completed successfully.";
    }

    protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
    {
        if (e.Exception.Data["GUID"] != null)
        {
            ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message +
                " When reporting this error use the following ID: " +
                e.Exception.Data["GUID"].ToString();
        }
        else
        {
            ScriptManager1.AsyncPostBackErrorMessage = 
                "The server could not process the request.";
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>PageRequestManager endRequestEventArgs Example</title>
    <style type="text/css">
    body {
        font-family: Tahoma;
    }
    #AlertDiv{
    left: 40%; top: 40%;
    position: absolute; width: 200px;
    padding: 12px; 
    border: #000000 1px solid;
    background-color: white; 
    text-align: left;
    visibility: hidden;
    z-index: 99;
    }
    #AlertButtons{
    position: absolute;
    right: 5%;
    bottom: 5%;
    }
    </style>
</head>
<body id="bodytag">
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" 
                               OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"
                               runat="server" />

            <script type="text/javascript" language="javascript">
                var divElem = 'AlertDiv';
                var messageElem = 'AlertMessage';
                var bodyTag = 'bodytag';
                Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
                function ToggleAlertDiv(visString)
                {
                     if (visString == 'hidden')
                     {
                         $get(bodyTag).style.backgroundColor = 'white';                         
                     }
                     else
                     {
                         $get(bodyTag).style.backgroundColor = 'gray';                         

                     }
                     var adiv = $get(divElem);
                     adiv.style.visibility = visString;

                }
                function ClearErrorState() {
                     $get(messageElem).innerHTML = '';
                     ToggleAlertDiv('hidden');                     
                }
                function EndRequestHandler(sender, args)
                {
                   if (args.get_error() != undefined)
                   {
                       var errorMessage = args.get_error().message;
                       args.set_errorHandled(true);
                       ToggleAlertDiv('visible');
                       $get(messageElem).innerHTML = errorMessage;
                   }
                }
            </script>
            <asp:UpdatePanel runat="Server" UpdateMode="Conditional" ID="UpdatePanel1">
                <ContentTemplate>
                    <asp:Panel ID="Panel1" runat="server" GroupingText="Update Panel">
                        <asp:Label ID="UpdatePanelMessage" runat="server" />
                        <br />
                        Last update:
                        <%= DateTime.Now.ToString() %>
                        .
                        <br />
                        <asp:Button runat="server" ID="Button1" Text="Submit Successful Async Postback"
                            OnClick="SuccessProcessClick_Handler" OnClientClick="ClearErrorState()" />
                        <asp:Button runat="server" ID="Button2" Text="Submit Async Postback With Error"
                            OnClick="ErrorProcessClick_Handler" OnClientClick="ClearErrorState()" />
                        <br />
                    </asp:Panel>
                </ContentTemplate>
            </asp:UpdatePanel>
            <div id="AlertDiv">
                <div id="AlertMessage">
                </div>
                <br />
                <div id="AlertButtons" >
                    <input id="OKButton" type="button" value="OK" 
                           runat="server" onclick="ClearErrorState()" />
                </div>
           </div>
      </div>
    </form>
</body>
</html>

詳細については、「ASP.NET UpdatePanel コントロールのエラー処理のカスタマイズ」を参照してください。

パネルのアニメーション化

UpdatePanel コントロールをアニメーション化して、コンテンツが変更されたことをユーザーに通知する方法を次の例に示します。LinkButton コントロールをクリックすると、UpdatePanel コントロールの周囲に境界線が短時間表示されます。

<%@ Page Language="VB" %>

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

<script runat="server">
    Protected Sub ChosenDate_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim dt As New DateTime()
        DateTime.TryParse(ChosenDate.Text, dt)

        CalendarPicker.SelectedDate = dt
        CalendarPicker.VisibleDate = dt

    End Sub
    Protected Sub Close_Click(ByVal sender As Object, ByVal e As EventArgs)
        SetDateSelectionAndVisible()        
    End Sub

    Protected Sub ShowDatePickerPopOut_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
        DatePickerPopOut.Visible = Not (DatePickerPopOut.Visible)

    End Sub

    Protected Sub CalendarPicker_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs)
        SetDateSelectionAndVisible()        
    End Sub

    Private Sub SetDateSelectionAndVisible()
        If (CalendarPicker.SelectedDates.Count <> 0) Then
            ChosenDate.Text = CalendarPicker.SelectedDate.ToShortDateString()
        End If
        DatePickerPopOut.Visible = False
    End Sub

    Protected Sub SubmitButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        If (Page.IsValid) Then
            MessageLabel.Text = "An email with availability was sent."
        Else
            MessageLabel.Text = ""
        End If
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        CompareValidatorDate.ValueToCompare = DateTime.Today.ToShortDateString()
        ExtraShow1.Text = DateTime.Today.AddDays(10.0).ToShortDateString()
        ExtraShow2.Text = DateTime.Today.AddDays(11.0).ToShortDateString()
    End Sub


    Protected Sub ExtraShow_Click(ByVal sender As Object, ByVal e As EventArgs)
        ChosenDate.Text = CType(sender, LinkButton).Text        
    End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Calendar Popup Example</title>
    <style type="text/css">
        body {
            font-family: Tahoma;
        }
        .PopUpCalendarStyle
        {
              background-color:lightblue;
              position:absolute;
              visibility:show;
              margin: 15px 0px 0px 10px;
              z-index:99;   
              border: solid 2px black;
        }
        .UpdatePanelContainer
        {
            width: 260px;
            height:110px;
        }

    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <script type="text/javascript">
        Type.registerNamespace("ScriptLibrary");
        ScriptLibrary.BorderAnimation = function(color, duration) {
            this._color = color;
            this._duration = duration;
        }
        ScriptLibrary.BorderAnimation.prototype = {
            animatePanel: function(panelElement) {
                var s = panelElement.style;
                s.borderWidth = '1px';
                s.borderColor = this._color;
                s.borderStyle = 'solid';
                window.setTimeout(
                    function() {{ s.borderWidth = 0; }},
                    this._duration
                );
            }
        }
        ScriptLibrary.BorderAnimation.registerClass('ScriptLibrary.BorderAnimation', null);

        var panelUpdatedAnimation = new ScriptLibrary.BorderAnimation('blue', 1000);
        var postbackElement;
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);

        function beginRequest(sender, args) {
            postbackElement = args.get_postBackElement();
        }
        function pageLoaded(sender, args) {
            var updatedPanels = args.get_panelsUpdated();
            if (typeof(postbackElement) === "undefined") {
                return;
            } 
            else if (postbackElement.id.toLowerCase().indexOf('extrashow') > -1) {
                for (i=0; i < updatedPanels.length; i++) {            
                    panelUpdatedAnimation.animatePanel(updatedPanels[i]);
                }
            }

        }
        </script>
        <h1>Tickets</h1>
        <p>
            <strong>Latest News</strong> Due to overwhelming response, we
            have added two extra shows on:
            <asp:LinkButton ID="ExtraShow1" runat="server" OnClick="ExtraShow_Click" />
            and
            <asp:LinkButton ID="ExtraShow2" runat="server" OnClick="ExtraShow_Click" />.
            Don't forget curtain time is at 7:00pm sharp. No late arrivals.
        </p>
        <hr />
        <div class="UpdatePanelContainer">
            <asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow1" />
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow2" />
                </Triggers>
                <ContentTemplate>
                    <fieldset >
                        <legend>Check Ticket Availability</legend>Date
                        <asp:TextBox runat="server" ID="ChosenDate" OnTextChanged="ChosenDate_TextChanged" />
                        <asp:ImageButton runat="server" ID="ShowDatePickerPopOut" OnClick="ShowDatePickerPopOut_Click"
                            ImageUrl="../images/calendar.gif" AlternateText="Choose a date."
                            Height="20px" Width="20px" />
                        <asp:Panel ID="DatePickerPopOut" CssClass="PopUpCalendarStyle"
                            Visible="false" runat="server">
                            <asp:Calendar ID="CalendarPicker" runat="server" OnSelectionChanged="CalendarPicker_SelectionChanged">
                            </asp:Calendar>
                            <br />
                            <asp:LinkButton ID="CloseDatePickerPopOut" runat="server" Font-Size="small"
                                OnClick="Close_Click" ToolTip="Close Pop out">
                            Close
                            </asp:LinkButton>
                        </asp:Panel>
                        <br />
                        Email
                        <asp:TextBox runat="server" ID="EmailTextBox" />
                        <br />
                        <br />
                        <asp:Button ID="SubmitButton" Text="Check" runat="server" ValidationGroup="RequiredFields"
                            OnClick="SubmitButton_Click" />
                        <br />
                        <asp:CompareValidator ID="CompareValidatorDate" runat="server"
                            ControlToValidate="ChosenDate" ErrorMessage="Choose a date in the future."
                            Operator="GreaterThanEqual" Type="Date" Display="None" ValidationGroup="RequiredFields" EnableClientScript="False"></asp:CompareValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorDate" runat="server"
                            ControlToValidate="ChosenDate" Display="None" ErrorMessage="Date is required."
                            ValidationGroup="RequiredFields" EnableClientScript="False"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail"
                            runat="server" ControlToValidate="EmailTextBox" Display="None"
                            ValidationGroup="RequiredFields" ErrorMessage="The email was not correctly formatted."
                            ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$" EnableClientScript="False"></asp:RegularExpressionValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail"
                            runat="server" ValidationGroup="RequiredFields" ControlToValidate="EmailTextBox"
                            Display="None" ErrorMessage="Email is required." EnableClientScript="False"></asp:RequiredFieldValidator><br />
                        <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                            ValidationGroup="RequiredFields" EnableClientScript="False" />
                        <asp:Label ID="MessageLabel" runat="server" />
                    </fieldset>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

<%@ Page Language="C#" %>

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

<script runat="server">
    protected void ChosenDate_TextChanged(object sender, EventArgs e)
    {
        DateTime dt = new DateTime();
        DateTime.TryParse(ChosenDate.Text, out dt);

        CalendarPicker.SelectedDate = dt;
        CalendarPicker.VisibleDate = dt;
    }
    protected void Close_Click(object sender, EventArgs e)
    {
        SetDateSelectionAndVisible();
    }

    protected void ShowDatePickerPopOut_Click(object sender, ImageClickEventArgs e)
    {
        DatePickerPopOut.Visible = !DatePickerPopOut.Visible;
    }

    protected void CalendarPicker_SelectionChanged(object sender, EventArgs e)
    {
        SetDateSelectionAndVisible();
    }

    private void SetDateSelectionAndVisible()
    {
        if (CalendarPicker.SelectedDates.Count != 0)
            ChosenDate.Text = CalendarPicker.SelectedDate.ToShortDateString();
        DatePickerPopOut.Visible = false;
    }

    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            MessageLabel.Text = "An email with availability was sent.";
        }
        else
        {
            MessageLabel.Text = "";
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        CompareValidatorDate.ValueToCompare = DateTime.Today.ToShortDateString();
        ExtraShow1.Text = DateTime.Today.AddDays(10.0).ToShortDateString();
        ExtraShow2.Text = DateTime.Today.AddDays(11.0).ToShortDateString();
    }

    protected void ExtraShow_Click(object sender, EventArgs e)
    {
        ChosenDate.Text = ((LinkButton)sender).Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Calendar Popup Example</title>
    <style type="text/css">
        body {
            font-family: Tahoma;
        }
        .PopUpCalendarStyle
        {
              background-color:lightblue;
              position:absolute;
              visibility:show;
              margin: 15px 0px 0px 10px;
              z-index:99;   
              border: solid 2px black;
        }
        .UpdatePanelContainer
        {
            width: 260px;
            height:110px;
        }

    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <script type="text/javascript">
        Type.registerNamespace("ScriptLibrary");
        ScriptLibrary.BorderAnimation = function(color, duration) {
            this._color = color;
            this._duration = duration;
        }
        ScriptLibrary.BorderAnimation.prototype = {
            animatePanel: function(panelElement) {
                var s = panelElement.style;
                s.borderWidth = '1px';
                s.borderColor = this._color;
                s.borderStyle = 'solid';
                window.setTimeout(
                    function() {{ s.borderWidth = 0; }},
                    this._duration
                );
            }
        }
        ScriptLibrary.BorderAnimation.registerClass('ScriptLibrary.BorderAnimation', null);

        var panelUpdatedAnimation = new ScriptLibrary.BorderAnimation('blue', 1000);
        var postbackElement;
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);

        function beginRequest(sender, args) {
            postbackElement = args.get_postBackElement();
        }
        function pageLoaded(sender, args) {
            var updatedPanels = args.get_panelsUpdated();
            if (typeof(postbackElement) === "undefined") {
                return;
            } 
            else if (postbackElement.id.toLowerCase().indexOf('extrashow') > -1) {
                for (i=0; i < updatedPanels.length; i++) {            
                    panelUpdatedAnimation.animatePanel(updatedPanels[i]);
                }
            }

        }
        </script>
        <h1>Tickets</h1>
        <p>
            <strong>Latest News</strong> Due to overwhelming response, we
            have added two extra shows on:
            <asp:LinkButton ID="ExtraShow1" runat="server" OnClick="ExtraShow_Click" />
            and
            <asp:LinkButton ID="ExtraShow2" runat="server" OnClick="ExtraShow_Click" />.
            Don't forget curtain time is at 7:00pm sharp. No late arrivals.
        </p>
        <hr />
        <div class="UpdatePanelContainer">
            <asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow1" />
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow2" />
                </Triggers>
                <ContentTemplate>
                    <fieldset>
                        <legend>Check Ticket Availability</legend>Date
                        <asp:TextBox runat="server" ID="ChosenDate" OnTextChanged="ChosenDate_TextChanged" />
                        <asp:ImageButton runat="server" ID="ShowDatePickerPopOut" OnClick="ShowDatePickerPopOut_Click"
                            ImageUrl="../images/calendar.gif" AlternateText="Choose a date."
                            Height="20px" Width="20px" />
                        <asp:Panel ID="DatePickerPopOut" CssClass="PopUpCalendarStyle"
                            Visible="false" runat="server">
                            <asp:Calendar ID="CalendarPicker" runat="server" OnSelectionChanged="CalendarPicker_SelectionChanged">
                            </asp:Calendar>
                            <br />
                            <asp:LinkButton ID="CloseDatePickerPopOut" runat="server" Font-Size="small"
                                OnClick="Close_Click" ToolTip="Close Pop out">
                            Close
                            </asp:LinkButton>
                        </asp:Panel>
                        <br />
                        Email
                        <asp:TextBox runat="server" ID="EmailTextBox" />
                        <br />
                        <br />
                        <asp:Button ID="SubmitButton" Text="Check" runat="server" ValidationGroup="RequiredFields"
                            OnClick="SubmitButton_Click" />
                        <br />
                        <asp:CompareValidator ID="CompareValidatorDate" runat="server"
                            ControlToValidate="ChosenDate" ErrorMessage="Choose a date in the future."
                            Operator="GreaterThanEqual" Type="Date" Display="None" ValidationGroup="RequiredFields" EnableClientScript="False"></asp:CompareValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorDate" runat="server"
                            ControlToValidate="ChosenDate" Display="None" ErrorMessage="Date is required."
                            ValidationGroup="RequiredFields" EnableClientScript="False"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail"
                            runat="server" ControlToValidate="EmailTextBox" Display="None"
                            ValidationGroup="RequiredFields" ErrorMessage="The email was not correctly formatted."
                            ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$" EnableClientScript="False"></asp:RegularExpressionValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail"
                            runat="server" ValidationGroup="RequiredFields" ControlToValidate="EmailTextBox"
                            Display="None" ErrorMessage="Email is required." EnableClientScript="False"></asp:RequiredFieldValidator><br />
                        <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                            ValidationGroup="RequiredFields" EnableClientScript="False" />
                        <asp:Label ID="MessageLabel" runat="server" />
                    </fieldset>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

詳細については、「チュートリアル : ASP.NET UpdatePanel コントロールのアニメーション化」を参照してください。

参照

概念

ASP.NET PageRequestManager クラスの概要