Pass javascript array to C# via json
11,027
Solved similar issue by this way:
JS code (part of processing function):
var ords = [];
$(".order-count-input").filter(function() {
return $(this).val() > 0;
}).each(function() {
ords.push({
GoodsId: $(this).attr("goodsId"),
Amount: $(this).val()
});
});
var data = {
orders: ords,
orderId: id
};
var params = {
url: actionUrl,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(data),
success: function (data) {
window.location.replace(data.redirect);
}
};
$.ajax(params);
Controller action:
[HttpPost]
public JsonResult PostOrder(long orderId, PostOrderViewModel[] orders)
Model:
[Serializable]
public class PostOrderViewModel
{
public long GoodsId { get; set; }
public int Amount { get; set; }
}
Author by
gvd
Updated on June 04, 2022Comments
-
gvd almost 2 years
I´m using this javascript array:
var exportOptions = [{ jobName: ""}, {exportType: ""}, {attachToEmail: ""}, {distributorName: ""}, {vistaNumber: ""}, {customerName: ""}, {competitors: ""}, {agreementType: ""}, { annualPotential: "" }, {businessCase: "" }];
And I passing to ASP.NET codebehind(C#) with this code:
$.ajax({ type: 'POST', url: 'Epad.aspx/generateReport', data: "{'columnList': '" + columnList + "', 'exportOptions':" + JSON.stringify( exportOptions ) + "}", contentType: 'application/json; charset=utf-8', dataType: 'json', async: true, cache: false, });
And reading in C# with this method:
public static void generateReport(string columnList, Object exportOptions) {}
columnList is a string variable this values I can retrieved from C# but the exportOptions's values I cannot see in the debugger... I can see the names of the exportOptions array key in Object exportOptions(C# Object) but never pass the values...
Can anybody help me with this?
-
gvd over 10 yearsThanks! With this very good example I can pass and read the array values to code behind... But now I can't access to array values in Javascript either by index or by key.... Any other help will be appreciated....
-
gvd over 10 yearsOpsss! Sorry for not update... I found that I can iterate array of object with two for in... like this.... for (var index in exportOptionsList) { var obj = exportOptionsList[index]; for (var key in obj) { alert("key: " + key + " value: " + obj[key]); } }