I would like to collect some data using AngularJS and post it back to my ASP.NET WebAPI controller.
I have defined my business object like this (which just aims to record overall annual petrol consumption along with consumption every month):
public class PetrolViewModel
{
public double petrol_annual { get; set; }
public int petrol_measure { get; set; }
public List<Month> months { get; set; }
}
public class Month
{
public double jan { get; set; }
public double feb { get; set; }
}
In my Angular code I have:
var app = angular.module('petrol', []);
app.controller('PetrolController', function ($scope, $http) {
$scope.petrol = {};
$scope.petrol.months = {};
$scope.sendForm = function() {
$http({
method: 'Post',
url: 'api/values',
data: $scope.petrol
}).success(function (data, status, headers, config) {
console.log(data);
console.log(status);
console.log(headers);
}).error(function (data, status, headers, config) {
console.log(data);
console.log(status);
console.log(headers);
});
};
});
When I submit the form data and leave the WebApi controller to receive an anonymous object it seems to work and I get my form data:
But, if I change this and try to pass in the ViewModel I defined earlier I get a null object being passed in:
I want to take full advantage of the ASP.NET features to automatically map the matching names and deliver me a populated Object that I can then handle in my code. I don't want to have to map the anonymous object to the ViewModel.
So, the programming question is: How do I make sure my AngularJS object can be matched to a ViewModel?
In tutorials I've been watching this seems to "just work" for everyone else so they tend not to cover it in much detail.
Here is the JSON that is being sent up, according to Fiddler:
{"months":{"jan":"10","feb":"10","mar":"10","apr":"10","may":"10","jun":"10","jul":"10","aug":"10","sep":"5","oct":"5","nov":"20","dec":"10"},"petrol_annual":"120","petrol_measure":"1"}