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?
return json_encode([], JSON_FORCE_OBJECT); it returns "{}" instead of {} only without the double quotes.
If you want to check if your response is not empty try : if ( json. length == 0 ) { console. log("NO DATA!") }
An empty string (response body with length 0) is invalid JSON.
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.
As of asp.net mvc 5 you could simple write:
Json(new EmptyResult(), JsonRequestBehavior.AllowGet)
if (portfolioManagerPortalData.salesData.myYTDSalesClients == null) {
returnJsonResult = Json(new object[] { new object() }, JsonRequestBehavior.AllowGet);
}
else {
returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With