I am trying to post a complex object from angular to my webapi the obeject looks like this
{
Name: "test",
Tax: 23,
Addresses: [ {
country: "ro",
city: "bucharest"
},
{
country: "fr",
city "paris"
}]}
and the object from server
public class Model {
public Model (){
Addresses = new List<Address>();
}
public string Name {get; set;}
public int Tax {get; set;}
public List<Address> Addresses {get; set;}
}
and Address has 2 string properties
my old application was written in MVC5 webapi2 and using angularjs $http service and the object was mapping perfectly, now I changed to MVC6 (asp.net 5) and if I remove the array from my javascript object it's working perfecyly but I don't have the array, if I add it than the object on server is NULL.
My question is: How can I send an array as object property from angularjs using $resource service to mvc6 controller?
Finally I made it work, my example below:
test1.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<script type="text/javascript" src="test1.js"></script>
<div ng-controller="TestController">
<div>Test</div>
</div>
</body>
</html>
test1.js
var myApp = angular.module('myApp', []);
myApp.controller('TestController', ['$scope', '$http', function ($scope, $http) {
var dataObj = {
Name: "test",
Tax: 23,
Addresses: [{
country: "ro",
city: "bucharest"
},
{
country: "fr",
city: "paris"
}]
}
$http({
url: 'http://localhost:1522/api/values',
method: 'POST',
data: JSON.stringify(dataObj),
dataType: 'json'
}).success(function (data) {
debugger;
alert("OK");
//TODO.....
}).error(function (data) {
//TODO....
});
}]);
On the screenshot you can see my solution folders and breakpoint after POST:
Replace URLs with your domain and navigate to http://yourdomain/test.html via browser for run your angular app.
PS: It example works when your angular app and web api in the same domain. If you want separate them (move angular app to another domain or project) you should config CORS - How do you enable cross-origin requests (CORS) in ASP.NET 5 & MVC 6 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.