달력

12022  이전 다음

  •  
  •  
  •  
  •  
  •  
  •  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  •  
  •  
  •  
  •  
  •  

[ajax.asp.net 포럼에서 펌]


atlas 에서는 <ErrorTemplate> 에다가 설정 해놨었는데, 조금 바뀌었습니다.

예제에는 DIV 로 배경색 바꿔서 div 로 처리하는데

저같은 경우는 masterPage 에다 ajaxToolkit 에 있는 ModalPopupExtender 으로

처리했습니다.


Customizing Error Handling for UpdatePanel Controls

Introduction

When an error occurs during partial-page updates in UpdatePanel controls, by default a script alert box is displayed with an error message. This tutorial shows you how to customize how the error is presented to the user and what information the message contains.

You can see the code in action in this tutorial by clicking the Run It buttons. To implement the procedures in your own development environment you need:

  • Visual Web Developer Express Edition or Visual Studio 2005.

  • The latest release of Microsoft ASP.NET AJAX installed and configured. For more information, see Installing ASP.NET AJAX.

  • An ASP.NET AJAX Web site.

To customize error handling in server code

  1. Create a new page and switch to Design view.

  2. In the AJAX Extensions tab of Toolbox, double-click the ScriptManager control and the UpdatePanel control to add them to the page.

  3. Add two TextBox controls, a Label control, a Button control, and some text inside of the UpdatePanel control. Set the text of the button to Calculate.

    Your page will look like the following:

    UpdatePanel Tutorial
  4. Double-click the Calculate button and add the following code for its event handler.

    CS

    protected void Button1_Click(object sender, EventArgs e){    try    {        int a = Int32.Parse(TextBox1.Text);        int b = Int32.Parse(TextBox2.Text);        int res = a / b;        Label1.Text = res.ToString();    }    catch (Exception ex)    {        if (TextBox1.Text.Length > 0 && TextBox2.Text.Length > 0)        {            ex.Data["ExtraInfo"] = " You can't divide " +                TextBox1.Text + " by " + TextBox2.Text + ".";        }        throw ex;    }        }

    VB

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)    Try        Dim a As Int32        a = Int32.Parse(TextBox1.Text)        Dim b As Int32        b = Int32.Parse(TextBox2.Text)        Dim res As Int32 = a / b        Label1.Text = res.ToString()    Catch ex As Exception        If (TextBox1.Text.Length > 0 AndAlso TextBox2.Text.Length > 0) Then            ex.Data("ExtraInfo") = " You can't divide " & _              TextBox1.Text & " by " & TextBox2.Text & "."        End If        Throw ex    End TryEnd Sub

    The event handler code contains a try-catch statement. In the try block, the code divides the values from the text boxes. If the operation fails, code in the catch block adds the extra string information ExtraInfo to the exception and then rethrows the exception without handling it.

  5. Switch to Design view and select the ScriptManager control.

  6. In the toolbar of the Properties window, click the Events button and then double-click the AsyncPostBackError box to create a handler for that event.

    UpdatePanel Tutorial
  7. Add the following code to the AsyncPostBackError event handler.

    CS

    protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e){    if (e.Exception.Data["ExtraInfo"] != null)    {        ScriptManager1.AsyncPostBackErrorMessage =            e.Exception.Message +            e.Exception.Data["ExtraInfo"].ToString();    }    else    {        ScriptManager1.AsyncPostBackErrorMessage =            "An unspecified error occurred.";    }}

    The code checks whether the ExtraInfo data item was defined for the exception. If so, the AsyncPostBackErrorMessage property is set to the string value. Otherwise, a default error message is created.

  8. Save your changes and then press CTRL+F5 view the page in a browser.

  9. Add a number greater than zero to each text box and click the Calculate button to demonstrate a successful postback.

  10. Change the second text box input to 0 and click the Calculate button to create an error condition.

    The browser displays a message box that contains the message set in the server code.

    UpdatePanel Tutorial
    note

    The style of the alert message box depends on what browser you are using, but the message is the same in all browsers.

    To see the full example in action, click the Run It button below.

Using Client Script to Customize Error Handling

The preceding procedure demonstrated how to customize errors during partial-page rendering by using setting properties of the server ScriptManager control. The following procedure builds on the customization by using the client PageRequestManager class to display the error in a <div> element instead of using the default browser alert message box.

To customize error handling in client script

  1. In the page you created earlier, switch to Source view

  2. Add the following markup to the page:

    CS

        <div id="AlertDiv" language="javascript" onclick="return AlertDiv_onclick()">        <div id="AlertMessage">        </div>        <br />        <div id="AlertButtons">            <input id="OKButton" type="button" value="OK" runat="server" onclick="ClearErrorState()" />        </div>    </div></div>

    VB

        <div id="AlertDiv" language="javascript" onclick="return AlertDiv_onclick()">        <div id="AlertMessage">        </div>        <br />        <div id="AlertButtons">            <input id="OKButton" type="button" value="OK" runat="server" onclick="ClearErrorState()" />        </div>    </div></div>

    The markup includes elements that you can use to display partial-page rendering errors. It defines a <div> element named AlertDiv that contains two other <div> elements. One of the nested <div> elements contains an <input> control that will enable users to hide the <div>.

  3. Add the following style markup in the <head> element.

    CS

    <style type="text/css">#UpdatePanel1 {  width: 200px; height: 50px;  border: solid 1px gray;}#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>

    VB

    <style type="text/css">#UpdatePanel1 {  width: 200px; height: 50px;  border: solid 1px gray;}#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>

    The styles make the error information stand out visually from the rest of the page content.

  4. Switch to Design view and verify that your page looks like the following:

    UpdatePanel Tutorial
  5. In the drop-down list at the top of the Properties window, select the DOCUMENT element (which represents the <body> element on the page) and set its Id property to bodytag.

    UpdatePanel Tutorial
  6. Switch to Source view.

  7. Add the following <script> block anywhere after the <asp:ScriptManager> element.

    CS

    <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;       if (args.get_response().get_statusCode() == '200')       {           errorMessage = args.get_error().message;       }       else       {           // Error occurred somewhere other than the server page.           errorMessage = 'An unspecified error occurred. ';       }       args.set_errorHandled(true);       ToggleAlertDiv('visible');       $get(messageElem).innerHTML = errorMessage;   }}</script>

    VB

    <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;       if (args.get_response().get_statusCode() == '200')       {           errorMessage = args.get_error().message;       }       else       {           // Error occurred somewhere other than the server page.           errorMessage = 'An unspecified error occurred. ';       }       args.set_errorHandled(true);       ToggleAlertDiv('visible');       $get(messageElem).innerHTML = errorMessage;   }}</script>

    This script does the following:

    • Defines a handler for the endRequest event of the PageRequestManager class. In the handler, the code displays the AlertDiv<div> element if there is an error condition.

    • Defines the ToggleAlertDiv function, which hides or shows the AlertDiv element and changes the color of the page based if there was an error condition.

    • Defines the ClearErrorState function, which hides the error message UI.

  8. Save your changes and then press CTRL+F5 view the page in a browser.

  9. Add a number greater than zero to each text box and click the Calculate button to demonstrate a successful postback.

  10. Change the second text box input to 0 and click the Calculate button to demonstrate an error condition.

    The custom AlertDiv element is displayed instead of default alert message box. The following figure shows an example of the error condition.

    UpdatePanel Tutorial

    To see the full example in action, click the Run It button below.

Review

This tutorial showed ways you can extend error handling during partial-page rendering by writing JavaScript code. In server code you can customize error handling by using the AsyncPostBackErrorMessage property and the AsyncPostBackError event of the ScriptManager control. In client code you can customize error handing by using the endRequest event of the PageRequestManager class.

This topic is ASP.NET AJAX pre-release documentation and is unsupported by Microsoft. Blank topics are included as placeholders and existing content is subject to change in future releases.

Posted by tornado

댓글을 달아 주세요