Thursday, September 1, 2011

Passing arrays from jQuery to C# Webservice

Step 1:
Download json2.js from https://github.com/douglascrockford/JSON-js
Include in your <head>
<script type="text/javascript" src="scripts/json2.js"></script>


Step 2:
Assuming you are populating an array from a select list, create and populate an array

var Voltages = new Array();
// AddedVoltage is my select list
$("#AddedVoltage option").each(function () {
        Voltages.push($(this).val());
});

Step 3:
Convert your array to a json string using json2.js
var jsonString = JSON.stringify(Voltages)


Step 4:
You can now pass the jsonString in your ajax request and recieve it as a string in your webservice.

Step 5:
Download jayrock json from http://code.google.com/p/jayrock/downloads/detail?name=jayrock-0.9.12915.zip&can=2&q= and add reference to your .net project.
More info here (http://msdn.microsoft.com/en-us/library/bb299886.aspx)

Step 6:
You can now convert the received json string in your web service to a list using

public List<String> ConvertToList(string jsonString)
    {
        List<string> SelectedVoltages = new List<string>();
        using (JsonTextReader reader = new JsonTextReader(new StringReader(jsonString)))
        {
            while (reader.Read())
            {
                if (reader.TokenClass == JsonTokenClass.String)
                {
                    SelectedVoltages.Add(reader.Token.Text);
                }
            }
        }
        return SelectedVoltages;
    }



No comments:

Post a Comment