2

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?

3
  • Please see the documentation; the data are sent as application/x-www-form-urlencoded by default. You'll likely want to use JSON: contentType: "application/json" Commented Aug 12, 2018 at 12:43
  • Possible duplicate of ajax post on MVC .NET does not pass array correctly Commented Aug 12, 2018 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 Commented Aug 13, 2018 at 8:08

1 Answer 1

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.

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.