Uncaught TypeError: Cannot use 'in' operator to search for '' in JSON string

爱⌒轻易说出口 提交于 2019-12-03 02:01:29

You need to parse the string in your populateValue variable to an object:

prePopulate: $.parseJSON(populateValue)

Or alternatively, in plain JS:

prePopulate: JSON.parse(populateValue)

You may get this error if you are using a string as an array. Say that if you got a json from an ajax, and you forgot to parse the result, and using the result as an array. The remedy is as above, to parse the json before using it.

user4359691

Your server side code means .CS page where you have written your WebMethod, should always return .ToList() means array of json

Here is my .CS page code:

WebMethod

public static string PopulateDetails(Guid id){
    var prx = new ProductProxy();
    var result = prx.GetFirstorDefault(id); // this method is having List<ClassObject> return type
    return JsonConvert.SerializeObject(result);
}

Then in my jQuery post method:

$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    url: "Productjq.aspx/PopulateDetails",
    data: JSON.stringify({id: id}), // This is Id of selected record, to fetch data
    success: function(result) {
        var rspns = eval(result.d); // eval is used to get only text from json, because raw json looks like "Id"\"1234"

        $.each(rspns, function() {
            $('#<%=txtProductName.ClientID %>').val(this.Name);
        });
    },
    error: function(xhr, textStatus, error) {
        alert('Error' + error);
    }
});

I was getting this error as well.

C# Api returning Serialized Dictionary data.

return JsonConvert.SerializeObject(dic_data);
return new JavaScriptSerializer().Serialize(dic_data);

Kept on getting this error message, until i just returned the Dictionary data directly without trying to Serialize

return dic_data;

No more errors on the browser side. Not sure why.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!