I have a object in my javascript with a object array inside it. I want to send it to my controller via a ajax call. But my list never seems to get populated in my controller. I make my machineList object as following:
var machineList = JSON.stringify({ 'machineList': objects.machines });
Console.log of this object
{"machineList":[{"Id":1,"Labour":"Hard","EnlistedMachine":"BEXTE","Type":"dz","Identifier":"ddd","IdentifierCode":"ddd"},{"Id":2,"Labour":"Easy","EnlistedMachine":"BEXTEss","Type":"dz","Identifier":null,"IdentifierCode":null}]}
My data object that gets send looks like this
var data = {
SalesPrice: $("#SalesPrice").val(),
machineList: machineList
};
Ajax call:
$.ajax({
url: currenturl + "/MyXmlAction",
data: data,
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
success: function (type) {
// data is your result from controller
if (type.success) {
XML = type.json;
}
},
error: function (xhr) {
alert('error');
}
});
My viewmodel looks like:
public class ContractViewModel
{
public string SalesPrice { get; set; }
List<MachineListDto> machineList = new List<MachineListDto>();
}
My controllerMethod looks like:
public ActionResult MyXmlAction(ContractViewModel data)
{
//Code
return Json(new { success = true, data }, JsonRequestBehavior.AllowGet);
}
MachineListDto
public class MachineListDto
{
public int Id { get; set; }
public string EnlistedMachine { get; set; }
public string Type { get; set; }
public string Labour { get; set; }
public string Identifier { get; set; }
public string IdentifierCode { get; set; }
}
}
Data object after changes by Tetsuya implemented
{"SalesPrice":"1000","machineList":[{"Id":1,"Labour":"Hard","EnlistedMachine":"BEXTE","Type":"dz","Identifier":"ddd","IdentifierCode":"ddd"},{"Id":2,"Labour":"Easy","EnlistedMachine":"BEXTEss","Type":"dz","Identifier":null,"IdentifierCode":null}]}
I tried doing the same I saw in the following post: Passing ListObject to controller
var data = JSON.stringify({ SalesPrice: $("#SalesPrice").val(), machineList: objects.machines });
(you stringify the whole object, not parts of it ). And your model must have properties, not fields -public List<MachineListDto> machineList { get; set; }
type: "GET",
- it must be a POST (a GET has no body)