简体   繁体   中英

Passing data from Ajax to controller in asp.net mvc

I have a viewModel

public class School
{
    public int SchoolId { get; set; }
    public int BuildingId { get; set; }
    public int FloorId { get; set; }
    public int PlannedBy { get; set; }

    public IEnumerable<HeadCountPerRoom> HeadCountPerRoom{ get; set; }
}

And my controller looks like this:

public JsonResult SaveHeadCount(IEnumerable<School>schoolViewModel,int action)
{
    // my code
}

I have written the javascript model and ajax:

function myfuncton() {
    var HeadCountPerRoom=[];
    var MasterEntry=[];
    HeadCountPerRoom.push({
        Month: month,
        Year: year,
        HeadCountId: seatCountID,
        SeatCount: SeatCount,
    });
    masterEntry= JSON.stringify({
        schoolViewModel:{ 
        SchoolId: SchoolId,
        BuildingId: BuildingId,
        FloorId: FloorId,
        PlannedBy: PlannedBy,
        HeadCountPerRoom: HeadCountPerRoom
    },
    action:3
});

 $.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    url: "../myController/SaveHeadCount",
    data: masterEntry,
    success: function (data) {
        //code.
    }
})

In the controller I am getting null in the schoolViewModel parameter and for the action parameter I am getting the value. Why I am getting null ?

You are expecting a list of school and you your JS you're passing only ONE object. You should pass your model on your JS as an array:

    schoolViewModel: [
                      { 
                        SchoolId: SchoolId, 
                        BuildingId: BuildingId, 
                        FloorId: FloorId, 
                        PlannedBy: PlannedBy, 
                        HeadCountPerRoom: HeadCountPerRoom
                       }
                      ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM