ASP. NET Ajax getting started series: custom exception handling

Source: Internet
Author: User
ASP. NET Ajax getting started series: custom exception handling (conversion)

When updatepanel controls are asynchronously updated, if an error occurs, an alert dialog box is displayed by default, which is unfriendly to users, this article describes how to customize exception handling in the server and client scripts and translate them into official documents.

 

Main Content

1. Customize Exception Handling on the server

2. Customize Exception Handling in client scripts

 

1. Custom Exception Handling on the server

1. Add the ASPX page and switch to the design view.

2. Under the Ajax extensions tab in the toolbox, double-click the scriptmanager and updatepanel controls to add them to the page.

3. Add two Textbox, one label, one button, and some text in the updatepanel control, and set the text attribute value of the button to "Calculate ".

4. Double-click the calculate button and add the following code to event processing.

Protected void button#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;
}
}

The event processing code contains a try-Catch Block. Division is performed in try. If the operation fails, set extrainfo in catch and throw an exception again.

5. Switch to the design view and select the scriptmanager control.

6. In the toolbar of the Properties window, select the event button and double-click asyncpostbackerror.

7. Add the following code to the asyncpostbackerror event.

Protected void scriptmanagerpolicasyncpostbackerror (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 .";
}
}

Check whether the extrainfo of the exception is null and set it to asyncpostbackerrormessage of the scriptmanager control. If not set, a default exception is created.

8. Save and press Ctrl + F5 to run.

9. Enter a number greater than zero in each text box, and click the calculate button to submit.

10. Enter 0 in the second text box and Click Calculate. An exception is thrown. The browser will display a dialog box Indicating the information we set on the server.

Ii. Customize Exception Handling in client scripts

The preceding exception handling is performed on the server by setting the attributes of the scriptmanager control. The following describes how to use the pagerequestmanager class in the client script for exception handling, use the <div> element to replace the default alert dialog box of the browser.

1. Switch to the Code view on the page we created earlier.

2. Add the following HTML elements to the page (an error occurred in the official document)

<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>

3. Add the following STYLE tag to the head element.

<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>

4. Switch to the design view and make sure that your page is as follows.

5. Select the document element (corresponding to the <body> element) from the drop-down list in the Property Window and set the ID attribute value to bodytag.

6. Switch to the Code view.

7. Add the following <SCRIPT> code block.

<SCRIPT type = "text/JavaScript" Language = "JavaScript">

VaR divelem = 'alertdiv ';

VaR messageelem = 'alertmesse ';

VaR bodytag = 'bodytag ';

SYS. webforms. pagerequestmanager. getinstance (). add_endrequest (endrequesthandler );

Function togglealertdiv (visstring)

{

If (visstring = 'ddn ')

{

$ 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 ('did ');

}

Function endrequesthandler (sender, argS)

{

If (ARGs. get_error ()! = Undefined)

{

VaR errormessage;

If (ARGs. GET_RESPONSE (). get_statuscode () = '20140901 ')

{

Errormessage = args. get_error (). message;

}

Else

{

// Error occurred somewhere other than the Server Page.

Errormessage = 'an unspecified error occurred .';

}

Args. set_errorhandled (true );

Togglealertdiv ('visable ');

$ Get (messageelem). innerhtml = errormessage;

}

}

</SCRIPT>

In the code block, we mainly do the following:

1) define pagerequestmanager class endrequest event processing. In event processing, alertdiv is displayed when an error occurs.

2) define the togglealertdiv function. When an error occurs, it is used to show or hide the alertdiv element and change the background color of the page.

3) define the clearerrorstate function, which is used to hide the UI of the error message.

8. Save and press Ctrl + F5 to run.

9. Enter a number greater than zero in each text box, and click the calculate button to submit.

10. Enter 0 in the second text box and Click Calculate. An exception is thrown. In this case, the custom alertdiv will be displayed instead of the default alert dialog box, as shown in:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.