views:

1295

answers:

3

ValidateEvents is a great ASP.net function, but the Yellow Screen of Death is not so nice. I found a way how to handle the HttpRequestValidationException gracefully here, but that does not work with ASP.net AJAX properly.

Basically, I got an UpdatePanel with a TextBox and a Button, and when the user types in HTML into the Textbox, a JavaScript Popup with a Error message saying not to modify the Response pops up.

So I wonder what is the best way to handle HttpRequestValidationException gracefully? For "normal" requests I would like to just display an error message, but when it's an AJAX Request i'd like to throw the request away and return something to indicate an error, so that my frontend page can react on it?

A: 

hmmmm, it seems you would need to find some sort of JavaScript to check for html input or a client side validator.

Sara Chipps
A: 

That's what I would like to avoid if possible, but this seems to be much more complicated than expected.

Normally, everyone advises using the AsyncPostBackError of the ScriptManager, but this does not work if called on the Global.asax. Unfortunately, as the HttpRequestValidationException is emitted by the runtime, it never enters my code and I cannot do much within the Application_Error.

So yes, it needs to be indeed done in the JavaScript, I just hope there is a way to add a "hook" like the BeginRequestHandler-Function so that I don't have to "hack" Microsoft code. If I find a solution before someone else, i'll put it up here :-)

Michael Stum
+2  A: 

Found it and blogged about it. Basically, the EndRequestHandler and the args.set_errorHandled are our friends here.

<script type="text/javascript" language="javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequestHandler);

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);
        $get('<%= this.newsletterLabel.ClientID %>').innerHTML = errorMessage;
    }
}
</script>
Michael Stum