UpdatePanel in .NET 3.5 : displaying a C# exception in a javascript alert message box

No.of Views2469
Bookmarked0 times
Downloads 
Votes1
By  oudinia   On  16 Feb 2010 03:02:41
Tag : AJAX and Atlas , How to
UpdatePanel in .NET 3.5 : displaying a C# exception in a javascript alert message box
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In .net 2.0, when we used an update panel, we could throw an exception from C#, and it would automatically display it in a message box. Now, in .net 3.5, we need to add in manually a peace of javascript, in order to achieve the same effect, otherwise it shows up with the default javascript exceptions, even though it's a C# exception.

For some, this might seem another task to remember, yet, it's really nice, as it gives us control over the alert we want to show. here's what the javascript looks like : 

Code

//registers the event by adding it to the endrequests collections of the instance

//This will allow it to actually listen to the event when it happens, and execute

//the code in the onEndRequest function

function pageLoad() {

Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(onEndRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest);
}

//function which will execute after the C# code gets to its end

//it will then catch the exception and display it on the alert message box

//the substring is just to avoid having the full exception definition,

//and display only the message

function onEndRequest(sender, args) {

if (args.get_error() != null) {

var msg = args.get_error().message;

//this line can be customized to all another alert or messagebox component, such as RadAlert from telerik,

//in which case it would look like

radalert(msg.substring(msg.indexOf(":", 0) + 1), 380, 100, 'Warning');

//instead of

alert(msg.substring(msg.indexOf(":", 0) + 1))

args.set_errorHandled(true);

return false;

}

else

{ return false; }

}

 

this is it, once you add in a throw new Exception(message) to the button click event, you can test it all.Here's the complete code listing for a C# asp.net page : 

Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" language="javascript">

        //registers the event by adding it to the endrequests collections of the instance
        //This will allow it to actually listen to the event when it happens, and execute 
        //the code in the onEndRequest function
        function pageLoad() {
            Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(onEndRequest); //>>Key line of code for the correction
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest);
        }

        //function which will execute after the C# code gets to its end
        //it will then catch the exception and display it on the alert message box
        //the substring is just to avoid having the full exception definition, 
        //and display only the message
        function onEndRequest(sender, args) {
            if (args.get_error() != null) {
                var msg = args.get_error().message;
                alert(msg.substring(msg.indexOf(":", 0) + 1));
                args.set_errorHandled(true);
                return false;
            }
            else
            { return false; }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager runat="server" ID="script1" />
        <asp:UpdatePanel runat="server" ID="pnlExceptions">
            <ContentTemplate>
            <h4>Exceptions thrown from C#, and displayed in a javascript alert box (works with the update panel)</h4>
                <asp:Button runat="server" ID="txtExceptionInAlert" Text="Trigger Exception" OnClick="txtExceptionInAlert_Click" />
                <asp:Button ID="Button1" runat="server" Text="Asynchronous post back button" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

Code

 here's the code behind: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
///
/// throwing the exception at the click event
///
///
///
protected void txtExceptionInAlert_Click(object sender, EventArgs e)
{
throw new Exception("This is an exception thrown from C# code");
}
}

 

Further thoughts, how does this technique, using exceptions rather than diplaying alerts after catching the exceptions, affect memory performance for an asp.net application ?

 Sample Project Source

Download source files -3 kb

 
Sign Up to vote for this article
 
About Author
 
oudinia
Occupation-Not Provided
Company-Not Provided
Member Type-Fresh
Location-Not Provided
Joined date-13 Oct 2009
Home Page-Not Provided
Blog Page-Not Provided
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top