Mohammadalijf
Mohammadalijf

Reputation: 1377

send an object that have an array inside with ajax to a httppost method in mvc

how can i send an object that have an array inside with ajax to a httppost method in mvc? im using @Html.AntiForgeryToken() in my view so i need to use ajax. here is my method

[HttpPost]
[ValidateAntiForgeryToken()]
public RedirectResult MultipleChangeSignupStatus(int[] id, string status)
{
   some code here
}

and the ajax i am using with a Link Button is like this:

var ids = [1 ,2, 3 ,4 ,5];
var token = $(':input:hidden[name*="RequestVerificationToken"]');
var data = {};
data['id'] = ids;
data[token.attr('name')] = token.val();   
data['status'] = 'accept';

$.ajax({
          url: '@Url.Action("MultipleChangeSignupStatus" , "Administrator")',
          data: data,
          type: 'POST',
           success: function () {

                }
       });

but in controller method i get a null value for id. status parameter is correctly set to 'accept' though id is still null

Upvotes: 0

Views: 750

Answers (2)

user3559349
user3559349

Reputation:

Add the parameter traditional: true

$.ajax({
  url: '@Url.Action("MultipleChangeSignupStatus" , "Administrator")',
  data: data,
  type: 'POST',
  traditional: true,
  success: function () {
  }
});

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039548

Try to construct your data object like this:

var ids = [1, 2, 3, 4, 5];

var token = $(':input:hidden[name*="RequestVerificationToken"]');
var data = { };
data['status'] = 'accept';
data[token.attr('name')] = token.val();

for (var i = 0; i < ids.length; i++) {
    data['id[' + i + ']'] = ids[i];
}

Upvotes: 1

Related Questions