This is continuation from here
What's the correct way to create class in JavaScript and pass that to MVC controller
public class VesselDetail
{
public string VesselName { get; set; }
public string VesselData { get; set; }
}
public class MainModel
{
public List<VesselDetail> VesselDetails { get; set; }
}
I have created JavaScript models as follows
class VesselDetail {
VesselName;
VesselData;
}
class VesselDetails {
constructor() {
this.VesselDetails = [];
}
addVessel(VesselName,VesselData) {
let p = new VesselDetail();
p.VesselName= VesselName;
p.VesselData= VesselData;
this.VesselDetails.push(p);
return p;
}
}
class MainModel {
VesselDetails = {};
}
In my button click event I will bind the required and passing it to MVC controller as follows
let model= new MainModel();
let vesselDetail = new VesselDetails();
vesselDetail.addVessel("vesselName1", "vessel desc");
vesselDetail.addVessel("vesselName2", "vessel desc1");
model.VesselDetails= vesselDetail;
$.ajax({
url: url,
type: 'POST',
async: false,
data: '{mainModel: ' JSON.stringify(model) '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
},
error: function (request) {
}
});
But in the controller VesselDetails is getting as null, what was the correct way to pass list to mvc from JavaScript.
CodePudding user response:
Unfortunately you have a bug in your javascript classes - double VesselDetails. I offer to use this classes, this is more object oriented style.
class VesselDetail {
constructor(vesselName, vesselData) {
this.VesselName = vesselName;
this.VesselData = vesselData;
}
VesselName;
VesselData;
}
class MainModel {
VesselDetails=[];
addVesselDetails(...args) {
this.VesselDetails = args;
}
}
ajax
let model = new MainModel();
//using special function
model.addVesselDetails(
new VesselDetail("vesselName1", "vessel desc")
,new VesselDetail("vesselName2", "vessel desc2")
);
//or directly
model.VesselDetails.push(
new VesselDetail("vesselName1", "vessel desc"),
new VesselDetail("vesselName2", "vessel desc2")
);
$.ajax({
url: url,
type: 'POST',
async: false,
data: JSON.stringify(model),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
},
error: function (request) {
}
});
action
public JsonResult CreateVessel([FromBody]MainModel mainModel)
{
// some processing
return new JsonResult ( mainModel.VesselDetails[0].VesselName );
}