Parsing jQuery serialized data in C #

I have a ListBox on my page. I am making an AJAX call to the C # function, and I need to pass the values ​​of the selected elements. Here is 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 passed to the C # function is as follows:

lbItems=1&lbItems=3&lbItems=5

Is there a built-in C # function that can easily deserialize to convert values ​​to some kind of array? Or maybe there is a better way to pass data from jQuery?

+3
source share
3 answers

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

+2
source

Split.

Just use string.Split with an ampersand to get an array of strings that are your individual arguments. Then cut each of these lines into an equal sign to get a two-element array, where element 0 is the name var and element 1 is the value.

Code example:

    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]);
    }
+2
source

Source: https://habr.com/ru/post/1769419/


All Articles