javascriptjqueryajaxasp.net-mvc-4

Data format on the wire of AJAX Post


In my AJAX post call, I want the data to be formatted like this (when viewed in Chrome Network Headers details) - which is what the server side is expecting. The question is: how can I update the JS below to format the data like this:

percentages[0].Id:7
percentages[0].Percentage:26.1
percentages[1].Id:8
percentages[1].Percentage:20.3

but, the data is currently formatted like this

percentages[0][Id]:7
percentages[0][Percentage]:26.1
percentages[1][Id]:8
percentages[1][Percentage]:20.3

I am currently formatting the data like this in JS before I send it via AJAX

var params = {};
var dict = [];
for (var idx in data) {
    var item = {
        Id: idx,
        Percentage: data[idx]
    };
    dict.push(item);
}
params['percentages'] = dict;

where the data variable has data like this (when written to Chrome console):

Object {7: "26.1", 8: "20.3"}

Thanks in advance

Edit:
in response to @Bogangles request: I am using .NET and the structure I'm trying to fill is:

IEnumerable<PercentageViewModel> percentages

where PercentageViewModel is:

public class PercentageViewModel
{
    public int Id { get; set; }
    public string Percentage { get; set; }
}

Solution

  • This was the answer that allow the server side data structure to be populated properly

    var i = 0;
    for (var idx in data) {
        params['percentages[' + i + '].Id'] = data[idx].Id;
        params['percentages[' + i + '].Percentage'] = data[idx].Percentage;
        i++;
    }