Bassa
Bassa

Reputation: 13

How to redirect to error page from onexception method instead of returning to jQuery/Ajax call in c# mvc

I'm trying to redirect to an Error page inside onexception method when an exception occurs. But the thing is I have Ajax function, so even if I redirect inside onexception class, it does not redirect to error page and it always end up with executing Ajax function. Please can anyone suggest a solution for this.

This is my controller method and when exception throws, it will call to base controller on exception method.

 public ActionResult DeleteConfirmed(int id)
        {
            try
            {

                string displayMessage = string.Empty;
                //Delete ward details and check successfulness of the function and return json result
                if (wardManager.DeleteWard(id) == true)
                {
                    displayMessage = CustomEnumMessage.GetStringValue(ConfirmationMessages.ConfirmationErrorMsg);
                    return Json(new { Message = displayMessage });
                }
                //Return json result if unsuccessfull 
                else
                {
                    displayMessage = CustomEnumMessage.GetStringValue(ConfirmationMessages.ConfirmationRemovedMsg);
                    return Json(new { Message = displayMessage });
                }

            }
            catch (System.Exception ex)
            {
                throw ex;
            }

        }

This is my base controller onexception method

protected override void OnException(ExceptionContext filterContext)
        {
            //Get exception type
            System.Type ExceptionType = filterContext.Exception.GetType();


            if (ExceptionType.Name == "DbUpdateException")
            {
                ViewData["ErrorMessage"] = filterContext.Exception.InnerException.Message;
                this.View("DatabaseException", filterContext.Exception).ExecuteResult(this.ControllerContext);

            }
            else
            {
                ViewData["ErrorMessage"] = filterContext.Exception.Message;
                this.View("ApplicationException", filterContext.Exception).ExecuteResult(this.ControllerContext);
            }

}

This is my Ajax function

$.ajax({
                    type: "POST",
                    dataType: "json",
                    jsonpCallback: "onJSONPLoad",
                    url: '@Url.Action("Delete")',
                    data: $('#form').serialize(),
                    success: function (data) {
                        $('#submit').hide();
                        TriggerMsg(data.Message);
                    },
                    error: function (xhr) {
                        if (xhr.getResponseHeader('Content-Type').indexOf('application/json') > -1) {
                            var json = $.parseJSON(xhr.responseText);
                            alert(json.errorMessage);
                        }

                    }
                });

I built this Ajax function for only displaying Successful messages and it avoids me to redirecting to error page. The problem is even if i redirect to error page inside onexception method, finally fire into Ajax error: function and it does not redirect into DatabaseException or ApplicationException views. Can anyone suggest a solution for this issue.

Thanks

Upvotes: 1

Views: 3380

Answers (1)

krilovich
krilovich

Reputation: 3505

Your problem is that when you do a post from an ajax function, whatever result you have in your controller will always end up coming back to the success function.

What you want to do is return a url to your ajax function and from there redirect the user.

In your controller return the following

result = Json(new { redirect = Url.Action("ActionName", "ControllerName", new { area = "" }) });

Then in your javascript you will look for this redirect variable and set the window.location to it

success: function (data) {
     if (data.redirect) {
            window.location.href = data.redirect;
        }           
    },

If you also want to pass a message then you can probably put it in the session such as Session["ErrorMessage"] = error from the controller and use it the same way in your error view

Upvotes: 2

Related Questions