I have the following jquery –
var items = new Array();
items.push({
"Item1":$("myvalue").val(),
"Item2":$("myvalue2").val()
});
....
data: {
'items': JSON.stringify(items)
},
....
With the following deserialization code –
var js = new JavaScriptSerializer();
var myobj = js.Deserialize<JsonModel>(items);
To the following object –
public class JsonModel
{
public string Item1 { get; set; }
public string Item2 { get; set; }
}
here is the json string that is returned to my controller
[{\"Item1\":\"1|2|3|5\",\"Item2\":\"1\"}]
This is not working. When I run this code, I end up with an empty object.
However, if I do a replace on the json string and remove the [ and ], it deserialized with the correct data.
Am I handling this incorrectly – I would like to deserialize to my object without having to modify the json string.
Any thoughts would be great. Thanks.
JSON.stringify(items)is going to serialize to an array, becauseitemsis an array. What you probably want is to go:All I’ve really done here not used the
itemsarray.The only caveat is if you do in fact want to send an array of these objects back to your controller. If that is the case your deserialization code will need to look something like
and of course you will need to send an a serialized array back as you were doing before.