Passing an associative array using json: which type to expect in the controller?
asp.net-mvc, c#, json
Solution
This is what I do when using a POST command:
var data = {
values: items
}
var obj = $.toJSON(data);
$.ajax({
url: methodUrl,
type: 'POST',
async: false,
data: obj,
dataType: 'json',
success: function (data) {
//...
}
});
This should send through to your Controller properly and you shouldn't have to use a Dictionary object, you should match objects up from client side to server side. I'd use a custom object that has a `Guid` and a `int` as properties in it, and use that - .NET will match the two up. That being said, it's perfectly reasonable to use a Dictionary, but that's personal preference.
i.e.
public CustomObject
{
public Guid MyGuid { get; set; }
public int MyNumber { get; set; }
}
public ActionResult Method(List<CustomObject> values)
{
}
With multiple parameters:
items.SecondNumber = yourVariable;
// In reality, you'd have a loop around your items and set this SecondNumber.
var data = {
values: items
}
var obj = $.toJSON(data);
public CustomObject
{
public Guid MyGuid { get; set; }
public int MyNumber { get; set; }
public int SecondNumber { get; set; } // This is why we use CustomObject
}
Problem
On the client side I have an associative array where I store "Guid" - "int" pairs. I pass the array to the server by using json: ``` $.ajax({ url: methodUrl, type: 'POST', async: false, data: { values: items }, dataType: 'json', success: function (data) { //... } }); ``` The object I try to pass looks like this(taken from Chrome debugger): ``` items: Object 44f871e0-daee-4e1b-94c3-76d633a87634: 1 698ce237-3e05-4f80-bb0d-de948c39cd96: 1 ``` In the controller I have a method ``` public ActionResult Method(Dictionary<Guid, int> values) { } ``` However, property values remains null. With just a list of Guids on the client side and List in the controller everything works fine. I suspect that I should choose another type for values in the controller, not Dictionary. I also tried adding "traditional: true" to the ajax request, however with no success. Any advice is appreciated!