0

I need to post dictionary to server. My code works fine.

Server-side:

[HttpPost]
public JsonResult SomeMethod(Dictionary<string, string> someData) {
    SomeAction();
    return null;
}

Client-side:

postMethod = function() {
    var someData = {};
    someData["1"] = "1";
    someData["2"] = "2";
    $.ajax({
        url: '/SomeMethod/',
        type: 'POST',
        traditional: true,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
            someData: someData
        }),
    });
    return false;
};

But if i change type of someData in controllers method to Dictionary<int, int> and try to pass

someData[1] = 1;
someData[2] = 2;

someData in controllers method is empty.

Why? And what difference between passing dictionary of string and dictionary of integer?

user3272018
  • 2,309
  • 5
  • 26
  • 48
  • 1
    You are doing a different thing in javascript. `someData["1"] = "1"` is assigning 1 to `someData.1` whereas `someData[1]` is setting element 1 of the array `someData` to 1. Inspect the json that gets submitted it will be totally different. Remeber javascript doesn't have dictionaries or associative arrays, it just supports a similar syntax for assigning value to objects. – Ben Robinson Aug 04 '15 at 09:33
  • ok, i see, but is there the way to pass 'something' for `public JsonResult SomeMethod(Dictionary someData)` or i need to parse dictionary of string on server-side code? – user3272018 Aug 04 '15 at 09:38
  • The only way to pass integers to that controller is via `SomeMethod(Dictionary someData)`, passing `someData["1"] = 1;` from the JS code. – Jason Evans Aug 04 '15 at 09:43
  • Another technique for posting a dictionary is described in [this answer](http://stackoverflow.com/questions/28297075/transmit-javascript-object-into-controller-action-as-dictionary/28298048#28298048) –  Aug 04 '15 at 09:45

1 Answers1

0
You can try using Array ..

var someData = new Array();
someData.key1 = 1;
someData.key2 = 2;

$.ajax({
    url: '/SomeMethod/',
    type: 'POST',
    traditional: true,
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({
        someData: someData
    }),
});