gpt4 book ai didi

javascript - asp.net mvc 6 web api + Angular 资源帖子数组作为对象属性

转载 作者:行者123 更新时间:2023-11-28 06:57:25 25 4
gpt4 key购买 nike

我正在尝试将一个复杂的对象从 Angular 发布到我的 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 Controller ?

最佳答案

最后我成功了,我的例子如下:

测试1.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 后的断点:

enter image description here

将 URL 替换为您的域并导航至 http://yourdomain/test.html通过浏览器运行您的 Angular 应用程序。

P.S.:当您的 Angular 应用程序和 Web api 在同一域中时,该示例有效。如果你想将它们分开(将 Angular 应用程序移动到另一个域或项目),你应该配置 CORS - How do you enable cross-origin requests (CORS) in ASP.NET 5 & MVC 6 .

关于javascript - asp.net mvc 6 web api + Angular 资源帖子数组作为对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32467966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com