Passing an associative array using json: what type to expect in the controller?

On the client side, I have an associative array where I store pairs of "Guid" - "int". I pass the array to the server using json:

  $.ajax({
      url: methodUrl,
      type: 'POST',
      async: false,
      data: { values: items },
      dataType: 'json',
      success: function (data) {
          //...
      }
  });

The object I'm trying to transfer looks like this (taken from the 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, the property values ​​remain zero. Having only the Guides list on the client side and List in the controller, everything works fine. I suspect that I should choose a different type for the values ​​in the controller, and not in the dictionary. I also tried adding “traditional: true” to the ajax request, however without success.

Any advice is appreciated!

+5
source share
3 answers

, POST:

var data = {
   values: items
}

var obj = $.toJSON(data);

$.ajax({
      url: methodUrl,
      type: 'POST',
      async: false,
      data: obj,
      dataType: 'json',
      success: function (data) {
          //...
      }
  });

, Dictionary, . , Guid int , -.NET . , .

.

public CustomObject 
{
    public Guid MyGuid { get; set; }
    public int MyNumber { get; set; }
}

public ActionResult Method(List<CustomObject> values)
{

} 

:

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
}
+4

, - .

, , , javascript . , , js :

items : Array[2]
0: Object
key: "ddac666f-310f-4022-a22c-c542355b765e"
value: 1
1: Object
key: "ce9ae5a6-e6a6-4bb6-b61c-b1cc324be049"
value: 1

, .

    var obj = JSON.stringify(items);
    $.ajax({
        url: teilnahmen.AddNewTeilnahmenUrl,
        type: 'POST',
        traditional: true,
        dataType: 'json',
        data: obj,
        contentType: "application/json",
        success: function (data) {
            //...
        }
    });

:

    public ActionResult AddNewTeilnahmen(Dictionary<Guid, int> values)
    { ... }

- , , , , , .NET. , , .

+2

Anelook, javascript:

var items = [];
$(something).each(function (index, element) {
   var item = { "key": element.guid, "value": element.number };
   items.push(item);
});
0

All Articles