I'm working on ASP.Net App and I have a simple view model with a List property as:
public List<int> SelectedStations { get; set; } = new List<int>();
Then via javascript I populate an array as:
var stations=[];
stations.push({
StationId:grid.dataItem(this).StationId,
});
So If I debug this it return data as following:
So it works, now I have an Ajax call to send this view model to controller as:
var data = {
...
SelectedStations: stations
}
$.ajax({
url:'/Test/Create/',
data: AddAntiForgeryToken({ model: data }),
method: 'POST',
success: function(){
setTimeout(function() {
location.reload();
}, 1000);
},
});
But the controller is always receiving list as empty list, what am I doing wrong?
console.log(data)
result before send to ajax:
Controller receive it as:
CodePudding user response:
The controller expects an array of int like [4, 3]
in your controller, whereas the ajax calls sends a list of objects [{StationId: 4}, {StationId: 3}]
.
Even if each object contains a single int, the types don't match.
As solution, you can for instance build an array of numbers instead:
stations.push(grid.dataItem(this).StationId);
Alternatively, you can amend the controller and define another C# model that has a StationId property.