1

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:

enter image description here

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:

enter image description here

Controller receive it as:

enter image description here

5
  • What are the parameters of the controller function? Does it match what you are sending? Commented Nov 28, 2022 at 22:37
  • My controller is like: public async Task<IActionResult> Create(MyViewModel model), I'm sure the model it is working because I have more properties in and I'm receiving the correct data, but that list is always empty @hijinxbassist Commented Nov 28, 2022 at 22:41
  • What does console.log(data) show before doing the ajax call? Commented Nov 28, 2022 at 22:44
  • I add an image to my question of the console.log(data), also added how it is receiving on the controller @JonP Commented Nov 28, 2022 at 22:53
  • 1
    @Demian Your controller expects a list of numbers (List<int>) , but in javascript it's not an array of int, like [5, 6], it's an array of objects [{StationId: 5}, {StationId: 6}]. Either adapt the mapping on the controller or before the ajax call. Commented Nov 28, 2022 at 22:57

1 Answer 1

1

The controller expects an array of int like [4, 3], 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.