Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonResult - how to return an empty JSON result?

I have an ajax call that makes a GET request to one of my controllers action methods.

The ajax call is supposed to get a JSON response and use that to populate a datagrid. The callback function is supposed to fire and construct the grid and hide the loading indicator.

$.getJSON('@Url.Action("Data", "PortfolioManager")' + '?gridName=revenueMyBacklogGrid&[email protected]', function (data) {

                        ConstructrevenueMyBacklogGrid(data);
                        $('#revenueMyBacklogLoadingIndicator').hide();

                    });

The problem is when the object I am converting to a JsonResult object has no data - it's just an empty collection.

returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);

In this example it is the collection myYTDSalesClients that returns empty (which is ok and valid - sometimes there won't be any data).

The JSON object then returns an empty response (blank, nadda) and since it's not valid JSON, the callback function won't fire. Thus the loading indicator still shows and it looks like it's just loading forever.

So, how do I return an empty JSON result {} instead of a blank?

like image 419
richard Avatar asked Feb 25 '14 21:02

richard


People also ask

How do I return an empty JSON response?

return json_encode([], JSON_FORCE_OBJECT); it returns "{}" instead of {} only without the double quotes.

How check JSON result is empty?

If you want to check if your response is not empty try : if ( json. length == 0 ) { console. log("NO DATA!") }

Is Empty response valid JSON?

An empty string (response body with length 0) is invalid JSON.

What does JsonResult return?

Format-specific Action Results For example, returning JsonResult returns JSON-formatted data. Returning ContentResult or a string returns plain-text-formatted string data. An action isn't required to return any specific type.


2 Answers

As of asp.net mvc 5 you could simple write:

Json(new EmptyResult(), JsonRequestBehavior.AllowGet)
like image 124
Giovanni Romio Avatar answered Oct 10 '22 00:10

Giovanni Romio


if (portfolioManagerPortalData.salesData.myYTDSalesClients == null) {
    returnJsonResult = Json(new object[] { new object() }, JsonRequestBehavior.AllowGet);
}
else {
    returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);
}
like image 37
Andre Figueiredo Avatar answered Oct 10 '22 00:10

Andre Figueiredo