Skip to content Skip to sidebar Skip to footer

Create Javascript Class Which Holds The List And Pass It To Mvc Controller

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; s

Solution 1:

Unfortunately you have a bug in your javascript classes - double VesselDetails. I offer to use this classes, this is more object oriented style.

classVesselDetail {

        constructor(vesselName, vesselData) {
            this.VesselName = vesselName;
            this.VesselData = vesselData;
        }

        VesselName;
        VesselData;
    }

    classMainModel {

        VesselDetails=[];

        addVesselDetails(...args) {
        this.VesselDetails = args;
        }
   }
    

ajax

let model = newMainModel();

//using special function

model.addVesselDetails(
newVesselDetail("vesselName1", "vessel desc")
,newVesselDetail("vesselName2", "vessel desc2")
);

//or directly

    model.VesselDetails.push(
    newVesselDetail("vesselName1", "vessel desc"),
    newVesselDetail("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 processingreturnnewJsonResult ( mainModel.VesselDetails[0].VesselName );
}

UPDATE

Report class looks for me very alike MainModel class

classAttachment {

        constructor(fileName, fileType) {
            this.FileName = fileName;
            this.FileType = fileType;
        }

        FileName;
        FileType;
    }

    classReport {

        Attachments = [];

        addAttachments(...args) {
            this.Attachments = args;
        }
    }

and you can create instances the same way as it is using MainModel

Post a Comment for "Create Javascript Class Which Holds The List And Pass It To Mvc Controller"