asp.net ajax 中的错误实现自定义处理个人把它分为后台C#处理和前台javascript处理。因为不是学这个专业的,所以也没有兴趣或者精力去关注其中的原理呀,机制呀等等,现在只是碰到问题怎么解决它。
一、后台错误处理
前台页面代码
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<div>
<asp:ScriptManager ID="sm1" runat="server" OnAsyncPostBackError="sm1_AsyncPostBackError">
</asp:ScriptManager>
<asp:Button ID="btnTest" runat="server" Text="ErrorTest" OnClick="btnTest_Click" />
</div>
后台代码
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
protected void sm1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
ScriptManager.GetCurrent(this).AsyncPostBackErrorMessage = e.Exception;
}
protected void btnTest_Click(object sender, EventArgs e)
{
int i = 0, j = 1;
int tmp = j / i;
}
这个后台处理方式主要使用了ScriptManager控件中的GetCurrent(this)方法和AsyncPostBackErrorMessage属性
二、前台实现方式
页面代码
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<asp:ScriptManager ID="sm3" runat="server" AllowCustomErrorsRedirect="true">
</asp:ScriptManager>
<asp:UpdatePanel ID="upal2" runat="server">
<ContentTemplate>
<asp:Button ID="btn3" runat="server" Text="ErrorTest" onclick="btn3_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div id="divAysnErrorMessge" />
其中<div>标签主要是显示出错的内容,写好以上代码后编写js函数如下:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<script language="javascript" type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender,e)
{
e.set_errorHandled(true); //表示自定义显示错误, 将默认的alert提示禁止掉.
$get("divAysnErrorMessge").innerHTML = e.get_error().message;
});
</script>
后台代码
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
protected void btn3_Click(object sender, EventArgs e)
{
int i = 1, j = 0;
int tmp = i / j;
}