TheBoubou
TheBoubou

Reputation: 19933

ASP.NET MVC with jQuery : catch exception + display error message

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,

Upvotes: 2

Views: 3255

Answers (1)

Çağdaş Tekin
Çağdaş Tekin

Reputation: 16661

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
        }
    });
});

Upvotes: 3

Related Questions