Sperick
Sperick

Reputation: 2761

Error when Serializing Js array to MVC model collection

I have JQuery code for creating storing a collection of checked checkboxes boxes as an array. This array is stored as the value of a hidden field on my form with the ID of 'CheckedSubGroups. The hidden field has been given the name of a List from my controller:

Model:

public IList<int> SubtGroupPkids { get; set; }

Hidden Field on Form:

<input type="hidden" id="CheckedSubGroups" name="SubGroupPkids" value="[]" />

JQuery for adding items to the array.

$(".SubGroupCheckBoxes").on("click", function() {
            if ($(this).is(':checked')) {
                var subGroupArray = JSON.parse($("#CheckedSubGroups").val());
                subGroupArray.push($(this).attr('data-subGroupPkid'));
                $("#CheckedSubGroups").val(JSON.stringify(subGroupArray));

if I add a couple of items this array looks like (from the debugger):

[15330,16657]
[prototype]: []
length: 2
[0]: "15330"
[1]: "16657"

I then serialize the form using JQuery's .serialize method.

However I get a binding error where it fails to convert the array to the List.

The value '["15330","16657"]' is not valid for SubGroupPkids.

Where am I going wrong?

Upvotes: 0

Views: 86

Answers (1)

Khalid
Khalid

Reputation: 235

You will need to de-serialize the json array in the Controller

 var deserializer = new JavaScriptSerializer();
 subGroupPkIds = deserializer.Deserialize<List<int>>(serializedData "data submitted to your controller");

Upvotes: 1

Related Questions