mfriis
mfriis

Reputation: 217

Parsing an array of string to MVC method

Im trying to parse a simple array of guids/strings to json the json is used as a parameter on a post call to my controller.

I have been trying a lot of different things but i simply cant make the controller method see my List.

The array is built from checkbox values:

$('input:checkbox').click(function () {
        if ($(this).attr("checked") == true) {
            selected.push($(this).val());
        }
    });

and looks alright. then i try to convert it to JSON

$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }
        var json = {
            SelectedQuantities: arrayJson
        };

        $.ajax({
            url: "/MVC/Physical/SelectQuantities/@Model.TopID",
            type: "POST",
            data: JSON.stringify(json),
            dataType: "json",
            contentType: 'application/json',
            success: function (result) {
                debugger;
                if (result.status == 200)
                    location.replace = "/MVC/Physical/QuantitySummaryView/@Model.TopID"
                else {
                    //Handle error
                }

            }
        });
    });
});

My controller method looks as following:

public ActionResult QuantitySummaryView(Guid id, List<String> SelectedQuantities)

But the list is always null. I figured it was because the JSON list doesnt contain the array of GUIDs directly underneath it.

Can you help me get it nudged in place?

JSON (as seen by Chromes dev tools) looks as following:

{
"SelectedQuantities": {
    "0": "707c40bd-4434-41ed-80fd-4ac541a81e85",
    "1": "a8d78a4b-b107-4e1c-97b5-5d8abf530ba8",
    "2": "a19226cc-9b22-4174-97e3-bb003d4b2746"
}

}

Upvotes: 1

Views: 1922

Answers (3)

Christophe Geers
Christophe Geers

Reputation: 8962

For example:

A model which contains a collection of GUIDs:

public class GuidModel
{
    public GuidModel()
    {
        Guids = new List<Guid>();

        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
        Guids.Add(Guid.NewGuid());
    }

    public IList<Guid> Guids { get; set; }
}

The checkboxes are rendered by the view:

<% var index = 1; %>
    <% foreach(var guid in Model.Guids) { %>
        <input type="checkbox" value="<%= guid %>" name="guid<%= index %>" />
     <%: guid %>
     <br />
     <% index++; %>
<% } %>
<br />
<input type="button" value="Summarize" id="Summarize" />    

The JavaScript / jQuery:

<script type="text/javascript">
    var selected = [];

    $('input:checkbox').click(function () {
        if ($(this).attr("checked") == true) {
            selected.push($(this).val());
        }
    });

    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }

        var json = {
            SelectedQuantities: arrayJson
        };
        json = JSON.stringify(json);

        $.post("/Home/QuantitySummaryView?data=" + json);
    });
</script>

The action method in the controller:

[HttpPost]
public ActionResult QuantitySummaryView(string data)
{
    // Deserialize the string containing JSON serialized data
    JavaScriptSerializer jss = new JavaScriptSerializer();    
    //...
}

Upvotes: 0

Buildstarted
Buildstarted

Reputation: 26689

You don't need to stringify the json nor do you need to add the dual SelectedQuantities

$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (var i in selected) {
            arrayJson[i] = selected[i];
        }

        var json = {
            SelectedQuantities: arrayJson
        };
        //json = JSON.stringify(json);
        $.post("/Home/QuantitySummaryView/@Model.TopID", json, true);
    });
});

However, based on your code you'll only get the number of items checked (all of them equal to "on") You don't have any code to pass the name of the item that was checked, nor do you pass the ones that are not checked. So you might have to change your code anyway to handle name/value pairs.

Upvotes: 1

Martin
Martin

Reputation: 11041

I think you are serializing one too many times, and you have one too many layers. Try this:

I removed one of the SelectedQuantities, and change the ajax call.

$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }

        var json = {
            SelectedQuantities: arrayJson
        };

        $.ajax({
            url: "/MVC/Physical/QuantitySummaryView/@Model.TopID",
            type: "POST",
            data: JSON.stringify(json),
            dataType: "json",
            contentType: 'application/json'
        });
    });
});

Also, try Firebug, it will show you want was passed to the server, so you can make sure the json created and passed is correct.

Upvotes: 1

Related Questions