簡體   English   中英

asp.net MVC 6 Web API +角度資源發布數組作為對象屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM