[英]asp.net mvc 6 web api + angular resource post array as object property
I am trying to post a complex object from angular to my webapi the obeject looks like this 我正在尝试将一个复杂的对象从角度发布到我的webapi中,对象看起来像这样
{
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 和地址具有2个字符串属性
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. 我的旧应用程序是使用MVC5 webapi2编写的,并且使用angularjs $ http服务编写,并且该对象已完美映射,现在我更改为MVC6(asp.net 5),如果我从javascript对象中删除了数组,那么它就可以正常工作,但是我没有有数组,如果我添加它,则服务器上的对象为NULL。
My question is: How can I send an array as object property from angularjs using $resource service to mvc6 controller? 我的问题是:如何使用$ resource服务从angularjs将数组作为对象属性发送到mvc6控制器?
Finally I made it work, my example below: 最终,我成功了,下面的示例:
test1.html 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 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: 在屏幕截图上,您可以在POST之后看到我的解决方案文件夹和断点:
Replace URLs with your domain and navigate to http://yourdomain/test.html via browser for run your angular app. 用您的域替换URL,然后通过浏览器导航到http://yourdomain/test.html以运行您的角度应用程序。
PS: It example works when your angular app and web api in the same domain. PS:当您的角度应用程序和Web API在同一域中时,此示例有效。 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 . 如果要将它们分开(将角度应用程序移至另一个域或项目),则应配置CORS- 如何在ASP.NET 5和MVC 6中启用跨域请求(CORS) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.