napfernandes
napfernandes

Reputation: 1359

AngularJS object is not properly converted into a ViewModel .NET

I have an AngularJS directive which returns me an array with some values, like this below:

enter image description here

The AngularJS code I'm using to generate this object like above is:

//--------------------------
// service...

service.getSelectedOptions = function() {
    var options = [];
    for (var I = 0; I < service.optionList.length; ++I) {
        var availableOption = service.optionList[I];

        if (availableOption.selecionado !== '') {
            options.push(availableOption);
        }
    }
    return opcoes;
};

//--------------------------
// controller...
var options = [];
var list = OptionsService.getSelectedOptions();
for (var I = 0; I < list.length; ++I) {
    var option = list[I];
    options.push({ Handle: option.Handle, Selecionado: option.Selecionado });
}
console.log(options);

// Sending the values to backend...
doPost('..../SaveOptions', { options: options }, function (result) {  });

Ok, I created a ViewModel class to receive those objects into my controller.

public class OptionsViewModel {
    public int Handle { get; set; }
    public string Selecionado { get; set; }
}

My controller is declared like this below:

public JsonResult SaveOptions(OptionsViewModel[] options) {
    //...
}

The problem is: if I chose 4 options, the array in the backend has 4 options, but the values are not binded to the objects.

enter image description here

Why that? Anyone knows why? Thanks!!

Upvotes: 0

Views: 149

Answers (1)

napfernandes
napfernandes

Reputation: 1359

The solution was modify two parameters in the AJAX call:

  1. Set contentType: "application/json";
  2. Use JSON.stringify(parameters) to the parameters.

Thanks!

Upvotes: 1

Related Questions