views:

38

answers:

1

I have the following JavaScript to populate a dropdown. When I single step into populateResourceList, the value for jsonList is shown below the code. However, this method fails on the for statement with the error jsonList.Table is undefined

What am I doing wrong?

    function populateResourceList(jsonList) {
        var listItems = "";
        for (var i = 0; i < jsonList.Table.length; i++) {
            listItems += "<option value='" + jsonList.Table[i].id + "'>" + jsonList.Table[i].name + "</option>";
        }
        $("#<%=resourceList.ClientID %>").html(listItems);
    };

    $(function () {
        var sessionId = 554;
        var x = PageMethods.GetFreeResources(sessionId, function (result, response, context) {
            populateResourceList(result);
        });
    });

EDIT: jsonList looks like this:

'{"Table": [ {"id": "1", "name": "Billy Bester"}, {"id": "2", "name": "Marlene Smith"}, {"id": "3", "name": "John Mills"}, {"id": "4", "name": "Brady Kelly"}, {"id": "5", "name": "Andrew Peel"}, {"id": "6", "name": "Colin Clifford"}, {"id": "7", "name": "Kerri Steele"}, ]}' 
+1  A: 

Are you sure it is a literal and not a string?

Try this and let me know. The eval is evil but it will tell us if this is the direction we want to go.

function populateResourceList(jsonList) {
    eval("var list=" + jsonList + ";");
    var listItems = "";
    for (var i = 0; i < list.Table.length; i++) {
        listItems += "<option value='" + list.Table[i].id + "'>" + list.Table[i].name + "</option>";
    }
    $("#<%=resourceList.ClientID %>").html(listItems);
};
Sky Sanders
What, the jsonList? It's a string value, I just pasted it without quotes to be clear what quotes are actually part of it, and which surround it.
ProfK
OK, looks like it is a json string. updating answer....
Sky Sanders
Great, thanks. Now to work on that eval ;-)
ProfK
@ProfK - looks like you are using MSAJAX, which has Sys.Serialization.JavaScriptSerializer that you can use to deserialize json. A question could be asked: Why are you returning a string from your page method? just return the object and msajax will give you a javascript object on return? Am I missing something?
Sky Sanders
I return a string because I build my json as a string. The serializer works great, thanks twice.
ProfK
@ProfK - fair enough. cheers.
Sky Sanders