i am creating json string my javascript and sending it to my controller in mvc application. my code which create json string :
$('#btnassign').click(function () {
var arrPrice = "";
var arrMarkUP = "";
$("table tr").each(function () {
if ($(this).find('input:checkbox:first').is(':checked')) {
if ($(this).find('input.inputprice').val() != "") {
arrPrice += "{";
var price = $(this).find('input.inputprice').val();
var id = $(this).find('input[type=hidden]').val();
arrPrice += '"Id":"' + id + '","Price":"' + price + '"';
arrPrice += "},";
}
if ($(this).find('input.inputmarkup').val() != "") {
arrMarkUP += "{";
var price = $(this).find('input.inputmarkup').val();
var id = $(this).find('input[type=hidden]').val();
arrMarkUP += "Id:" + id + ",Price:" + price;
arrMarkUP += "},";
}
}
});
var lastindexp = arrPrice.lastIndexOf(",");
arrPrice = arrPrice.substring(0, lastindexp) + "|";
var lastindexm = arrMarkUP.lastIndexOf(",");
arrMarkUP = arrMarkUP.substring(0, lastindexm) + "|";
alert(arrPrice);
alert(arrMarkUP);
$("#hdPrice").val(arrPrice);
$("#hdMarkUP").val(arrMarkUP);
$("#AssignProductForm").submit();
});
});
my json string generates from above code :
{"Id":"1","Price":"4"},{"Id":"2","Price":"6"}
My Controller parsing code :
[HttpPost]
public ActionResult AddProducts(FormCollection collection, string txtsearch)
{
var ManualPricing = collection["hdPrice"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
JavaScriptSerializer ser = new JavaScriptSerializer();
var Manual = ser.Deserialize<PriceMargin>(ManualPricing[0]);
}
price margin is a class to which it should deserialize :
public class PriceMargin
{
public string Id { get; set; }
public string Price { get; set; }
}
line var Manual = ser.Deserialize(ManualPricing[0]); gives me an error :Invalid JSON primitive: {"Id":"2","Price":"9"}.
please help ASAP.
Solution :
var list = new JavaScriptSerializer().Deserialize<List<KeyValue>>(json);
public class KeyValue
{
public string key;
public string value;
}