views:

80

answers:

3

I have a ListBox on my page. I'm making an AJAX call to a C# function, and I need to pass the values of the selected items. Here's what I have:

$('#btnSubmit').click(function() {
    $.ajax({
        type: "POST",
        url: 'Default.aspx/GetSelectedValues',
        data: '{selectedValues: ' + $('#lbItems').serialize() + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess
    });
});

<select id="lbItems" multiple="multiple">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>


[System.Web.Services.WebMethod]
public static string GetSelectedValues(string selectedValues)
{
    //
}

The data being passed to the C# function looks like:

lbItems=1&lbItems=3&lbItems=5

Is there any built-in C# function that can deserialize that easily, to convert the values into an array of some sort? Or maybe there's a better way to pass the data from jQuery?

A: 

That type of format is actually be very easy to parse with the string class' Split function.

Just use string.Split with the ampersand to get an array of strings that are your individual arguments. And then slit each one of those string on the equal sign to get a two-element array where element 0 is the var name and the element 1 is the value.

Code sample:

    string data = "lbItems=1&lbItems=3&lbItems=5";

    string[] items = data.Split(new char[]{'&'});

    foreach (string item in items)
    {
        string[] vals = item.Split(new char[]{'='});
        Console.WriteLine(vals[0] + ": " + vals[1]);
    }
Paul Sasik
Each of the name-value pairs are going to be URL encoded, so you'll have to deal with that too.
Rei Miyasaka
+1  A: 

System.Web.HttpUtility.ParseQueryString

Rei Miyasaka
+2  A: 

If you pass the parameters in as JSON, .NET will automatically deserialize the JSON for you.

Dave Ward
That's actually my preferred method, but I don't know how to pass an array of values (in this case, the values of the selected options) through an AJAX call. I have a prior post about that here: http://stackoverflow.com/questions/3926098/passing-an-array-of-values-in-an-asp-net-jquery-ajax-post. If you know of a way to use JSON, I'd love to see an example.
Steven
I answered over on the other question, since it was more on-topic there.
Dave Ward
Awesome, thanks.
Steven