Reputation: 2394
[{prodId:'10',qnty:'12',total:'1200'},
{prodId:'11',qnty:'2',total:'10'},
{prodId:'4',qnty:'10',total:'50'}]
i have the following class
public class ListItem{
public int prodID {get;set;}
public int qnty {get;set;}
public decimal total {get;set;}
}
the above json array will be sent from ajax call to an action method. In the action method i need to build a List<ListItem>
collection from the json array. How do i do this?
UPDATES here is the controller
public class ShoppingCartController : Controller
{
public JsonResult AddToShoppingCart(string jsonString)
{
int carId = 0;
string[] str= jsonString.Split(',');
for (int i = 0; i < str.Length; i++)
{
if (str[i] == "cartId")
{
string tmp = str[i].Split(':').LastOrDefault();
carId = int.Parse(tmp);
if (carId == -1)
{
//create new cart
}
else {
}
}
}
}
Here is the ajax:
$('#addToCartForm #add').on('click', function () {
$.ajax({
url: 'ShoppingCart/AddToShoppingCart',
method: 'post',
data: JSON.stringify(item),
dataType: 'json',
success: function (data) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
Upvotes: 1
Views: 408
Reputation: 714
you can De-serialize you string variable to your object List
by Code
var obj = jsonString.Deserialize<List<ListItem>>();
public static T Deserialize<T>(this string json)
{
T returnValue;
using (var memoryStream = new MemoryStream())
{
var settings = new DataContractJsonSerializerSettings
{
DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("yyyy-MM-dd HH:mm:ssZ")
};
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null))
{
var serializer = new DataContractJsonSerializer(typeof(T),settings);
returnValue = (T)serializer.ReadObject(jsonReader);
}
}
return returnValue;
}
Deserialize JSON into C# dynamic object?
Upvotes: 0
Reputation:
Change you POST method to
public JsonResult AddToShoppingCart(List<ListItem> model)
and the script to
$('#addToCartForm #add').on('click', function () {
$.ajax({
url: '@Url.Action("AddToShoppingCart", "ShoppingCart")', // don't hard code
method: 'post',
data: JSON.stringify({ 'model': item }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
assuming item
is the javascript array your have shown. The DefaultModelBinder
will correctly bind the collection
Upvotes: 4
Reputation: 1235
You can use ToObject method of JArray class when the json structure same to C# class structure. like this:
List<ListItem> result = JArray.ToObject<List<ListItem>>();
Upvotes: 0