1

I'm using Jquery for my JSON post and get.

The problem I have is I don't know how to respond from my MVC controller to make it hit the 'failure'.

I'm using MVC.NET, I'm not using web.api

My ajax should be familiar (The code snippets has variables already defined):

   $.ajax({
            type: type,
            url: url,
            contentType: "application/json;",
            data: data,
            dataType: "json",
            success: function (response) {
                successDelegate(response); 
            },
            failure: function (e) {
                failDelegate(e.statusText); 
            },
            error: function (e) {
                errorDelegate(e.statusText); 
            }

The problem I have is every time I return it hits the success.

So my MVC controller could be

[HttpPost]
public JsonResult Create()
{
     //logic removed
     return Json(new { IsError = true, Message = "The captcha code is not vaid" });
}

I see why it's hitting the success ... it's returning as I want, and I could simply validate the IsError but it would be better to return it in a way where the AJAX knows if it's success or failure.

I have read Send JSON data via POST (ajax) and receive json response from Controller (MVC) but this about just receiving a response (which I have working), not about the type of response (how to make the response go to Failure, not sucess).

MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120
  • Possible duplicate of [Send JSON data via POST (ajax) and receive json response from Controller (MVC)](https://stackoverflow.com/questions/8517071/send-json-data-via-post-ajax-and-receive-json-response-from-controller-mvc) – Farhad Bagherlo Sep 19 '17 at 17:37
  • @FarhadBagherlo why is this a dupe? I know how to get a response. My post stages that it always hits success. My question is how to get the correct type of response in order to make it hit failure. – MyDaftQuestions Sep 19 '17 at 17:39
  • Possible duplicate of [Return JSON with error status code MVC](https://stackoverflow.com/questions/11370251/return-json-with-error-status-code-mvc) – Kolichikov Sep 19 '17 at 17:44
  • @Kolichikov, that... is a lot of code to return something but is the principal to simply thrown an exception? – MyDaftQuestions Sep 19 '17 at 17:47

2 Answers2

4

There is an easy way of returning ajax errors in MVC. I am doing it this way:

the controller:

    public JsonResult testCatch()
    {
        try
        {
            //some code here
            return Json(new { success = true, Message = "Success!" });

        }
        catch (Exception ex)
        {                
            Response.StatusCode = 500; //Write your own error code
            Response.Write(ex.Message);
            return null;
        }
    }

The View:

       $.ajax({
            url: '@Url.Action("testCatch", "Controller")',
            dataType: 'json',
        })
        .success(function (result) {
            //do something

        })
        .error(function (xhr) {
             alert(xhr.status +" :" + xhr.responseText);
        })

This way, if there is any error in the try block, .success()function is not invoked. Instead .error() is invoked.

oopsdazie
  • 716
  • 1
  • 7
  • 22
1

I assume, you are on a wrong path.

You always run into the code block for

success: function() {}

because this is the handle for successful requests. Having a false-flag like your "IsError" within your JSON response does not make your HTTP response unsuccessful.

Parse json within success-function and look for IsError with an if-else and then let your UI react on that. If your code hits the error-callback something is truly broken and out of your normal user experience. I've never heard of jQuery failure callback, but maybe I never stumbled over it.

Anyway: "success" means that jQuery could send the request and received an answer, so that is where you want to work.

iquellis
  • 979
  • 1
  • 8
  • 26
  • I agree. Failure indicates that the request *failed* and should have a different action taken than a request which succeeded but had other issues. – Travis J Sep 19 '17 at 18:03
  • Yes, this is actually what I was doing, but it felt wrong. However, your post makes sense. It did complete successfully so I should parse the response. Thanks – MyDaftQuestions Sep 19 '17 at 18:33