[英]asp.net mvc 6 web api + angular resource post array as object property
我正在尝试将一个复杂的对象从角度发布到我的webapi中,对象看起来像这样
{
Name: "test",
Tax: 23,
Addresses: [ {
country: "ro",
city: "bucharest"
},
{
country: "fr",
city "paris"
}]}
和来自服务器的对象
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;}
}
和地址具有2个字符串属性
我的旧应用程序是使用MVC5 webapi2编写的,并且使用angularjs $ http服务编写,并且该对象已完美映射,现在我更改为MVC6(asp.net 5),如果我从javascript对象中删除了数组,那么它就可以正常工作,但是我没有有数组,如果我添加它,则服务器上的对象为NULL。
我的问题是:如何使用$ resource服务从angularjs将数组作为对象属性发送到mvc6控制器?
最终,我成功了,下面的示例:
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....
});
}]);
在屏幕截图上,您可以在POST之后看到我的解决方案文件夹和断点:
用您的域替换URL,然后通过浏览器导航到http://yourdomain/test.html以运行您的角度应用程序。
PS:当您的角度应用程序和Web API在同一域中时,此示例有效。 如果要将它们分开(将角度应用程序移至另一个域或项目),则应配置CORS- 如何在ASP.NET 5和MVC 6中启用跨域请求(CORS) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.