views:

689

answers:

1

Hello,

I have this code :

    $(document).ready(function() {
    $('.DOFFDelete').click(function() {
        var id = $(this).attr("id");
        $.post("/Customer/DayOffDelete", { customerid: getCustomerId(), doffId: id }, function(data) {
            $("#myFormDOFF").html(data);
        });
    });
});

In the Controller, I have this :

        CustomerDayOff customerDayOff;
        try
        {
            .....             
        }
        catch (Exception ex)
        {
            return View("ErrorTest",ex.Message);
        }
        return View("CustomerDetail");

When an exception occurred, I'd like didn't change anything in "myFormDOFF" but display the exception message in "myFormMessage".

Questions : 1. In the jQuery code, how can I make the difference between a valid result and an exception ?

  1. Is there a way to use the the controller "Home" (or another shared controller) and "ShowError" action to display the error of all controllers by using for example RedirectToAction instead of return View("ErrorTest",ex.Message); ?

Thanks,

+2  A: 

I don't suggest catching all the exceptions in your controller action. Just catch the ones you can handle, if there's any. Otherwise let them be thrown.

As for jQuery side of the things, use the ajax method instead of post method to run different functions for different responses from your server.

//assuming you have a button/link with an ID of "myFormDOFF"
$("#myFormDOFF").click(function() {
    $.ajax({
        type: "POST",
        url: "/Customer/DayOffDelete",
        data: { customerid: getCustomerId(), doffId: id },
        success: function(msg){
            $("#myFormDOFF").html(msg);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //handle the error here
        }
    });
});
çağdaş
Thanks. But how can I call this when I press the button "DOFFDelete" ?
Kris-I
@kris You just replace this code with your current `$.post`-snippet.
peirix
@kris-i, I've edited the answer to show you how you can attach that function to an element's click event.
çağdaş
@çağdaş, juste one more thing.I check the content of the 3 parameters of error function. In any case, I have ONLY the text I put on my Exception in the controller like throw new Exception("MyTextToDisplay")
Kris-I
@Kris, I guess the errorThrown argument is only available when a JS expection occurs (I'm not sure though). You could try to access the XMLHttpRequest object's status property to see what kind of error occured (ie 500 = internal server error, 404 - page not found). XMLHttRequest object's responseText property should also be filled with the response from the server. For a full list of XMLHttpRequest's properties see : http://www.dynamicajax.com/fr/XmlHttpRequest_Properties-.html
çağdaş
I have to just parse the result just to get the title. That's ok.
Kris-I