Elad Lachmi
Elad Lachmi

Reputation: 10561

Return string array from asp.net web service to jquery

I have a web service which returns a string currently and I want it to return a string array. My js code looks like this:

function getMenu(menuID) {
    $("#open").css('display', 'block');
    $("#close").css('display', 'none');
    $('#flash_container').flash({
        swf: 'mainGallery.swf',
        width: "100%",
        height: 330,
        wmode: "transparent",
        quality: "high",
        flashvars: { XMLFile: 'xml/' + menuID + '.xml' }
    });

    $("div#panel").slideUp("slow", function() {
        var language;
        if (getParameterByName('language') == 'en')
            language = 1;
        else
            language = 0;

        GetMenu.CreateMenu(menuID, language, OnGotMenu, OnFail, "XmlDocument");

    });

}

function OnGotMenu(result) {
    var lblOutput = document.getElementById("lblOutput");
    lblOutput.innerHTML = result;

    $(".MenuList a:last").removeAttr('border-left');

    $("div#panel").slideDown("slow");
    $("#open").css('display', 'none');
    $("#close").css('display', 'block');
    fleXenv.fleXcrollMain("panel_content");
}

Now I return a string. I want to return string[].

How do I need to modify my js code to use this array?

Edit: Here is the c# code after the change proposed by @pukipuki (only the relevant part)

table.RenderControl(tw);
        string retVal = "[\"" + menuDIV + sb.ToString() + "\", \"" + currTitle + "\"]";
        return retVal.ToString();

Maybe I'm doing something wrong here.

Edit 2: Better version of the c# code:

table.RenderControl(tw);
    retArray[0] = menuDIV + sb.ToString();
    retArray[1] = currTitle;
    string retVal = jsSer.Serialize(retArray);
    return retVal;

But I still don't get an array I can access like:

var that = result[0];
var oranother = result[1];

etc.

Upvotes: 2

Views: 1475

Answers (2)

Elad Lachmi
Elad Lachmi

Reputation: 10561

Thank you all for your help, you pushed me in the right direction. The solution was to add [ScriptMethod(ResponseFormat=ResponseFormat.Json)]

Then I just return the string array as-is and the framework converts it to JSON. Back in the js code I can now just access the fields using result[0], result[1], etc.

Upvotes: 0

Timur Sadykov
Timur Sadykov

Reputation: 11377

You should return data in format like:

[ "array", "elements", "here" ]

and then you will be able to index through result.

Upvotes: 1

Related Questions