Search code examples
jqueryasp.netjsonajaxwebmethod

Receive and manipulate in a WebMethod an unknown number of name/value sent via Ajax


I want to send to a WebMethod an Ajax post with some data. In the original code I do not know how many pairs of data are, because they are dynamically, but for simplify I add only two data in this example:

$.ajax({
    url: 'dama-actions.aspx/UpdateDataAdvanced',
    type: "POST",
    data: "{data: {'one':'onevalue', 'two':'twovalue'}}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
    alert(data.d);
    }
});

Then, with WebMethod I need to read the data to know all the name/value couples. I try in many ways but I have not succeeded, the lstItems is ever empty. I add a foreach and a counter to see if the list fills, but not.

[WebMethod]
public static string UpdateDataAdvanced(object data)
{
    List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(data);

    int counter = 0;

    foreach (string item in lstItems)
    {
        counter = counter + 1;
    }

    return counter.ToString();
}

The final use is to read the couples and create dinamically an SQL statement to update a table. I know how manipulate data for my SQL statement, but at this time I need to know why my WebMethod not collect data.

Thank you for your help and excuse my bad english.


Solution

  • Just change the the type of your 'data' parameter into Dictionary<string, string>.

    public static string UpdateDataAdvanced(Dictionary<string, string> data)
    {
        // Further code
    }