[RESOLVED]Returning NULL thworing an Error

Hello,

Here is my Code. I am checking from database how many items are missing. If none of the items are missing, I am returning NULL. If any item is missing, I am returning that item.

Returning missing items working fine and going through success funtion. If count == 0 and returning null, it is going to error function.

 List<string> missingItems;
 var missingItemsNames= genericData.Where(m => !diffids.Contains(m.itemID)).ToList();

                if (missingItemsNames.Count > 0)
                {
                   missingItems= missingItemsNames.Select(a => a.Name).ToList();
                }
                else
                {
                   missingItems= null;
                  
                }
return this.Json(missingItems, JsonRequestBehavior.AllowGet);
                $.ajax({
                    type: "POST",
                    url: "missingItems",
                    data: { 'ID': ID},
                    traditional: true,
                    dataType: "json",
                 
                    success: function (result) {                       
                        if ($.trim(result)) {
                            debugger;                                                   

                        } else {
                            debugger;
                           
                        }
                    },
                    error: function () {
                        debugger;
                    }
                });

Hi,

Try to avoid returning null , it will impact the performance and when you trying to convert null to an object inside jquery it will throw an error,

Please try to return some meaningful value from code, like return 0 or -1  will help you to avoid those error

there is no json representation for null. you could return an empty object "{}" or array "[]"

Hi ramll,

For this issue, if there aren’t any data, you could return an empty collection.

List<string> missingItems=new List<string>();
 var missingItemsNames= genericData.Where(m => !diffids.Contains(m.itemID)).ToList();

                if (missingItemsNames.Count > 0)
                {
                   missingItems= missingItemsNames.Select(a => a.Name).ToList();
                }
     return this.Json(missingItems, JsonRequestBehavior.AllowGet);

On the other hand, to check whether the object is empty, please use
jQuery.isEmptyObject
function.

Best Regards

Starain

Leave a Reply