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.

        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 );
}

UPDATE

Report class looks for me very alike MainModel class

    class Attachment {

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

        FileName;
        FileType;
    }

    class Report {

        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"