开发者

Parse jQuery serialized data in C#

开发者 https://www.devze.com 2023-01-20 01:36 出处:网络
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:

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 GetSelectedV开发者_运维百科alues(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?


System.Web.HttpUtility.ParseQueryString


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


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]);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消