1

My Scenario :

My .getJson Method is in this skeleton.

   $.getJSON(url, { /*data*/ },

                          function (result) {                           
                                 /*Action BLOCK*/    
                                 if(result != null)
                                 { //Block 1 }
                                 else
                                 { //Block2 }
                            }
}

My Doubt:

This is my return statement in controller.

Case 1 :

 return Json(masterAccounts, JsonRequestBehavior.AllowGet)

Now If masterAccounts is null, then the getJSON is not at all going inside the Action Block. Though the status shows 200 OK, in response tab, it shows as No Response to show enter image description here

Case 2 :

  return Json(masterAccounts??new List<Account>(), JsonRequestBehavior.AllowGet);

Now, everything is working fine. In response tab I am getting as [] as expected.

My Question : Do the Action block of getJson executes even null value returned from server? I have tried this link., http://api.jquery.com/jQuery.getJSON/ But I saw no conditions like that.

In Mozilla too, I had same effect. The control is not going inside the Action Block.

Muthu Ganapathy Nathan
  • 3,199
  • 16
  • 47
  • 77

2 Answers2

1

As long as you get a 200 from the server, it'll go into your block. Just look at the doc :

jQuery.getJSON( url [, data ] [, success(data, textStatus, jqXHR) ] )

success(data, textStatus, jqXHR) Type: Function() A callback function that is executed if the request succeeds.

The only requirements for your callback to execute is that the request succeeds. Returned data can be empty JSON, it doesn't change the fact you responded with an HTTP 200 which means the request did was it was supposed to do. The reason it works with case 2 is because you're saying to instantiate a new empty List if masterAccount is null (which it is). Case 1 just sends null and it isn't valid JSON, therefore it's not firing the success callback.

If you want to properly handle errors, you need to use the HttpStatusCode enum corresponding to error codes :

Response.StatusCode = (int)HttpStatusCode.BadRequest;
actionResult = this.Content("Why it failed");
return actionResult;

To handle the error client side you need to use the error callback from JQuery.Ajax() (thus replacing getJson).

LMeyer
  • 2,570
  • 1
  • 24
  • 35
  • "Case 1 just sends null and it isn't valid JSON, therefore it's not firing the success callback." - If you see the http://stackoverflow.com/questions/17610156/do-the-action-block-of-getjson-executes-even-null-value-returned-from-server#answer-17610819 FSou1 too does the returns the same null. But It is working i his case. Why? Also, null is a valid JSON. Ref : http://stackoverflow.com/questions/8526995/is-null-valid-json-4-bytes-nothing-else – Muthu Ganapathy Nathan Jul 12 '13 at 09:25
  • @EAGER_STUDENT Answered. According to Jquery I think it isn't : http://api.jquery.com/jQuery.parseJSON/ See "even though those are not valid JSON" – LMeyer Jul 12 '13 at 09:27
  • But I got no exeception thrown. Also, as in the link will `return Json(null, JsonRequestBehavior.AllowGet);` this statement shouldnot be used as of Jquery 1.9+ – Muthu Ganapathy Nathan Jul 12 '13 at 09:32
  • @EAGER_STUDENT Try replacing your getJSON with ajax() (with datatype:json) and implement an error callback. Then you'll be able to log and see the exception. – LMeyer Jul 12 '13 at 09:39
  • Thanks a lot. using .fail() at the end of getJson call traced the bug. My Question now is., `return Json(null, JsonRequestBehavior.AllowGet);` is not a valid statement?? – Muthu Ganapathy Nathan Jul 12 '13 at 10:00
  • @EAGER_STUDENT Well, the statement is valid (from a C# perspective), but the response on the JQuery side isn't. The exception occurs when parseJSON is invoked, so it's happening client side. So the problem is coming from the way Jquery treats null, not from the statement itself. – LMeyer Jul 12 '13 at 10:03
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/33346/discussion-between-eager-student-and-shinosha) – Muthu Ganapathy Nathan Jul 12 '13 at 10:04
1

Ok, i tried to make your example myself and that's what i have:

HomeController.cs

    public JsonResult GetJSON()
    {
        var t = new { a = "1", b = new int[] { 5, 6, 7 } };

        //return Json(t, JsonRequestBehavior.AllowGet);
        return Json(null, JsonRequestBehavior.AllowGet);
    }

View.cshtml

<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script>
    $.getJSON('/home/getjson', {}, function (result) {
        if (result != null) {
            console.log('result != null');
            console.log(result);
        }
        else {
            console.log('result == null');
            console.log(result);
        }
    });
</script>

Result

enter image description here enter image description here

I didn't have any problem with condition and Json result- every block was executed.

If it could help you, i used VS 2012, MVC 4, jQuery 1.8.2

Maxim Zhukov
  • 10,060
  • 5
  • 44
  • 88