views:

48

answers:

4

I'm having some issues catching error messages from a controller via .ajax error. The script is called by a jQuery UI Dialog popup. Any help would be appreciated.

Here's the code snippet from my controller

            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Content("There was an error in your request.", MediaTypeNames.Text.Plain);

and here's the jQuery script:

function submitFormWithAjax(form) {
    form = $(form);
    $.ajax({
        url: form.attr('action'),
        data: form.serialize(),
        type: (form.attr('method')),
        dataType: 'text',
        error: function(data) {
            $('#result').html(data);
        },
        success: function(data) {
            $('#result').html(data);
            setTimeout("reloadPage()", 500);
        }
    });
  return false;
}

The error: function(data) isn't reading the returned error message. Any suggestions?

+1  A: 

The signature for the error callback is function(xmlHttpRequest, textStatus, exceptionThrown).

Maybe you're looking at the wrong parameter?

Thomas
Thanks, I changed the code to error: function(xmlHttpRequest, textStatus, exceptionThrown) and I can access xmlHttepRequest. However, how do I attach my error message in the controller? I guess return Content("There was an error in your request.", MediaTypeNames.Text.Plain); isn't right.
Dean
I'm not really familiar with ASP.NET MVC, but my guess is you have to return a View. That's all I can offer thus far.
Thomas
+2  A: 

Try this:

    function submitFormWithAjax(form) {
    form = $(form);
    $.ajax({
        url: form.attr('action'),
        data: form.serialize(),
        type: (form.attr('method')),
        dataType: 'text',
        error: function(data) {
            $('#result').html(data);
        },
        success: function(xmlHttpRequest, textStatus, exceptionThrown) {
            $('#result').html(xmlHttpRequest.statusText);
            setTimeout("reloadPage()", 500);
        }
    });
  return false;
}
amurra
+1  A: 

It must be something about returning a BadRequest (error 400.) The error callback does seem to be called when the return code is Conflic (error 409).

Hector
+1  A: 

Thanks for everyone's help. I figured it out after some trial, all I needed to do was this in jQuery

    error: function(xhr, textStatus, exceptionThrown) {
        $('#result').html(xhr.responseText);
    },

and this in the controller

            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Content("There was an error in your request.");

Cheers

Dean