ASP.NET AJAX入门系列(8):自定义异常处理

UpdatePanel控件异步更新时,如果有错误发生,默认情况下会弹出一个Alert对话框显示出错误信息,这对用户来说是不友好的,本文看一下如何在服务端和客户端脚本中自定义异常处理,翻译自官方文档。

 

主要内容

1.在服务端自定义异常处理

2.在客户端脚本中自定义异常处理

 

一.在服务端自定义异常处理

1.添加ASPX页面并切换到设计视图。

2.在工具箱中AJAX Extensions标签下双击ScriptManagerUpdatePanel控件添加到页面中。

3.在UpdatePanel控件中添加两个TextBox,一个Label,一个Button和一些文字,并设置ButtonText属性值为“Calculate”。

4.双击Calculate按钮并添加如下代码到事件处理中。

None.gif protected   void  Button1_Click( object  sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
try
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
int a = Int32.Parse(TextBox1.Text);
InBlock.gif
InBlock.gif        
int b = Int32.Parse(TextBox2.Text);
InBlock.gif
InBlock.gif        
int res = a / b;
InBlock.gif
InBlock.gif        Label1.Text 
= res.ToString();
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
if (TextBox1.Text.Length > 0 && TextBox2.Text.Length > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ex.Data[
"ExtraInfo"= " You can't divide " +
InBlock.gif
InBlock.gif                TextBox1.Text 
+ " by " + TextBox2.Text + ".";
InBlock.gif
ExpandedSubBlockEnd.gif        }

InBlock.gif        
throw ex;
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

在事件处理代码中包含了一个try-catch语句块,在try中进行除法运算,如果运算失败,在catch中设置ExtraInfo信息并重新抛出异常。

5.切换到设计视图并选择ScriptManager控件。

6.在属性窗口中的工具栏中,选择事件按钮,并双击AsyncPostBackError

7.添加如下代码到AsyncPostBackError事件处理。

None.gif protected   void  ScriptManager1_AsyncPostBackError( object  sender, AsyncPostBackErrorEventArgs e)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
if (e.Exception.Data["ExtraInfo"!= null)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        ScriptManager1. AsyncPostBackErrorMessage 
=
InBlock.gif
InBlock.gif            e.Exception.Message 
+
InBlock.gif
InBlock.gif            e.Exception.Data[
"ExtraInfo"].ToString();
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif    
else
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{       ScriptManager1.AsyncPostBackErrorMessage =
InBlock.gif
InBlock.gif            
"An unspecified error occurred.";
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

检测异常的ExtraInfo是否为空,并设置为ScriptManager控件的AsyncPostBackErrorMessage,如果不设置则会创建一个默认的异常。

8.保存并按Ctrl + F5运行。

9.在每一个文本框中输入大于零的数,并单击Calculate按钮提交成功。

10.在第二个文本框中输入0,单击Calculate将会引发一个异常。浏览器将会显示一个对话框,提示的信息为我们在服务端设置的信息。

二.在客户端脚本中自定义异常处理

前面的异常处理是在服务端通过设置ScriptManager控件的属性来进行处理,下面将看一下如何在客户端脚本中使用PageRequestManager类来进行异常处理,并用<div>元素来代替浏览器默认的Alert对话框。

1.在我们前面创建的页面中,切换到代码视图。

2.添加如下的HTML元素到页面中(官方文档中有点错误)

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

3.在HEAD元素中添加如下样式标记。

ExpandedBlockStart.gif ContractedBlock.gif < style  type ="text/css" > dot.gif
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    #UpdatePanel1 
{dot.gif}{
InBlock.gif
InBlock.gif      width
: 200px; height: 50px;
InBlock.gif
InBlock.gif      border
: solid 1px gray;
InBlock.gif
ExpandedSubBlockEnd.gif    
}

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    #AlertDiv
{dot.gif}{
InBlock.gif
InBlock.gif    left
: 40%; top: 40%;
InBlock.gif
InBlock.gif    position
: absolute; width: 200px;
InBlock.gif
InBlock.gif    padding
: 12px; 
InBlock.gif
InBlock.gif    border
: #000000 1px solid;
InBlock.gif
InBlock.gif    background-color
: white; 
InBlock.gif
InBlock.gif    text-align
: left;
InBlock.gif
InBlock.gif    visibility
: hidden;
InBlock.gif
InBlock.gif    z-index
: 99;
InBlock.gif
ExpandedSubBlockEnd.gif    
}

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    #AlertButtons
{dot.gif}{
InBlock.gif
InBlock.gif    position
: absolute; right: 5%; bottom: 5%;
InBlock.gif
ExpandedSubBlockEnd.gif    
}

ExpandedBlockEnd.gif
None.gif
</ style >

4.切换到设计视图并确保你的页面如下所示。

5.在属性窗口中的下拉列表中选择DOCUMENT元素(它对应的是页面<Body>元素),设置Id属性值为bodytag

6.切换到代码视图。

7.添加如下<script>代码块。

ExpandedBlockStart.gif ContractedBlock.gif < script  type ="text/javascript"  language ="javascript" > dot.gif
InBlock.gif
InBlock.gif
var divElem = 'AlertDiv';
InBlock.gif
InBlock.gif
var messageElem = 'AlertMessage';
InBlock.gif
InBlock.gif
var bodyTag = 'bodytag';
InBlock.gif
InBlock.gifSys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
InBlock.gif
InBlock.gif
function ToggleAlertDiv(visString)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
InBlock.gif     
if (visString == 'hidden')
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif     
dot.gif{
InBlock.gif
InBlock.gif         $get(bodyTag).style.backgroundColor 
= 'white';                         
InBlock.gif
ExpandedSubBlockEnd.gif     }

InBlock.gif
InBlock.gif     
else
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif     
dot.gif{
InBlock.gif
InBlock.gif         $get(bodyTag).style.backgroundColor 
= 'gray';                         
InBlock.gif
InBlock.gif 
InBlock.gif
ExpandedSubBlockEnd.gif     }

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

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
function ClearErrorState() dot.gif{
InBlock.gif
InBlock.gif     $get(messageElem).innerHTML 
= '';
InBlock.gif
InBlock.gif     ToggleAlertDiv('hidden');                     
InBlock.gif
ExpandedSubBlockEnd.gif}

InBlock.gif
InBlock.gif
function EndRequestHandler(sender, args)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
InBlock.gif   
if (args.get_error() != undefined)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif
InBlock.gif       
var errorMessage;
InBlock.gif
InBlock.gif       
if (args.get_response().get_statusCode() == '200')
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif       
dot.gif{
InBlock.gif
InBlock.gif           errorMessage 
= args.get_error().message;
InBlock.gif
ExpandedSubBlockEnd.gif       }

InBlock.gif
InBlock.gif       
else
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif       
dot.gif{
InBlock.gif
InBlock.gif           
// Error occurred somewhere other than the server page.
InBlock.gif

InBlock.gif           errorMessage 
= 'An unspecified error occurred. ';
InBlock.gif
ExpandedSubBlockEnd.gif       }

InBlock.gif
InBlock.gif       args.set_errorHandled(
true);
InBlock.gif
InBlock.gif       ToggleAlertDiv('visible');
InBlock.gif
InBlock.gif       $get(messageElem).innerHTML 
= errorMessage;
InBlock.gif
ExpandedSubBlockEnd.gif   }

InBlock.gif
ExpandedSubBlockEnd.gif}

ExpandedBlockEnd.gif
None.gif
</ script >

在代码块中,主要做以下几件事:

1)定义PageRequestManager类的endRequest事件处理,在事件处理中,当有错误发生时将显示AlertDiv

2)定义ToggleAlertDiv函数,当有错误发生时它用来显示或者隐藏AlertDiv元素,并且改变页面的背景颜色。

3)定义ClearErrorState函数,它用来隐藏错误信息的UI

8.保存并按Ctrl + F5运行。

9.在每一个文本框中输入大于零的数,并单击Calculate按钮提交成功。

10.在第二个文本框中输入0,单击Calculate将会引发一个异常。这时自定义的AlertDiv将会显示出来代替了默认的Alert对话框,如下图所示:

[翻译自官方文档]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值