1

I am using the Map() functionality in ES6 to create a list of keypair values, making an ID number to a boolean value. I want to pass this Javascript object to an MVC 4 Controller.

Here's my Javascript:

var bankHolidays = new Map();
$('.bank-holiday-switch').each(function () {
    var id = $(this).attr('id');
    var isChecked = $(this).is(':checked');
    bankHolidays.set(id, isChecked);
});

$.ajax({
    url: '/AdminPanel/Settings/SaveBankHolidays',
    type: 'POST',
    data: { bankHolidays: bankHolidays },
    success: function (result) {
        alert("Success");
    }
});

I can console.log() the map object and see that it's being created as intended. However, when I pass it to this MVC Controller:

[HttpPost]
public JsonResult SaveBankHolidays(Dictionary<int, bool> bankHolidays)
{
   // DO stuff
}

..no error is thrown, but it just says the bankHolidays dictionary has 0 values in it. I can call other Actions in that Controller without issue. I have tried many different combinations of Dictionary<string, bool> to no avail.

Can somebody tell me what I am doing wrong?

MSOACC
  • 3,074
  • 2
  • 29
  • 50
  • Please see the [documentation](http://api.jquery.com/jquery.ajax/); the data are sent as `application/x-www-form-urlencoded` by default. You'll likely want to use JSON: `contentType: "application/json"` – Heretic Monkey Aug 12 '18 at 12:43
  • Possible duplicate of [ajax post on MVC .NET does not pass array correctly](https://stackoverflow.com/questions/25212591/ajax-post-on-mvc-net-does-not-pass-array-correctly) – Heretic Monkey Aug 12 '18 at 12:43
  • Is there a particular reason you want to use a `Map`? - you cannot sent a `Map` using ajax - it needs to be converted back to an `object` before posting –  Aug 13 '18 at 08:08

1 Answers1

2

In a http negotiation, xhr in this case, we must send strings, so you need some string representation of Map(), the best option, in my opinion, is to use a JSON stringify in some way, because the parse of JSON have a broad support among server side code:

var bankHolidays = new Map();

bankHolidays.set(1, 2);
bankHolidays.set(3, 4);

var result = JSON.stringify([...bankHolidays]);

console.log(result)

In your code something like :

$.ajax({
    url: '/AdminPanel/Settings/SaveBankHolidays',
    type: 'POST',
    data: JSON.stringify([...bankHolidays]),
    success: function (result) {
        alert("Success");
    }
});

In backend you have to parse the response, see this.

Emeeus
  • 5,072
  • 2
  • 25
  • 37