简体   繁体   English

从AngularJS到ASP.NET MVC5的模型

[英]Model from AngularJS to ASP.NET MVC5

I have some problems posting to my controller from Angular. 我从Angular发布到我的控制器时遇到一些问题。 If i post the variables separately, everything is fine, but when i combine my vars into one object that responds to my view model, it only recognises the ID but not the list of my PlayerViewModel.. 如果我分别发布变量,那么一切都很好,但是当我将var组合成一个对视图模型做出响应的对象时,它只能识别ID,而不能识别PlayerViewModel的列表。

Here are my viewModels: 这是我的viewModels:

public class PlayerViewModel
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class TeamViewModel
{
    public int ID { get; set; }
    public List<PlayerViewModel> Players;
}

This is my MVC-controller: 这是我的MVC控制器:

[HttpPost]
    public JsonResult IndexPost(int ID, List<PlayerViewModel> ListPlayers, TeamViewModel Team)
    {
        return Json(true, JsonRequestBehavior.AllowGet);
    }

This is my Angular code: 这是我的Angular代码:

$scope.players = [];
            $scope.playerA = { ID: 5, Name: "Player1" };
            $scope.playerB = { ID: 6, Name: "Player2" };
            $scope.playerC = { ID: 8, Name: "Player3" };
            $scope.players.push($scope.playerA);
            $scope.players.push($scope.playerB);
            $scope.players.push($scope.playerC);

            $scope.ID = 7;

            $scope.team = { ID: $scope.ID, Players: $scope.players };

            $scope.btnClick = function () {
                $http({
                    traditional: true,
                    url: "IndexPost",
                    method: "POST",
                    data: { 'ID': $scope.ID, 'ListPlayers': $scope.players, 'Team': $scope.team },
                    dataType: FormData
                }).success(function (data) {
                    $scope.finish = data;
                }).error(function (data) {
                    $scope.status = status;
                });
            }

This is my response in the controller: 这是我在控制器中的响应:

(It's an image in dropbox) (这是保管箱中的图片)

As you can see, the ID of my TeamViewModel is correct, but the List of PlayerViewModels won't fill in. Does anyone have an idea what i'm doing wrong? 如您所见,我的TeamViewModel的ID是正确的,但是PlayerViewModels的列表不会填写。有人知道我在做什么错吗?

Thank you!! 谢谢!!

Serialize your data with JSON.stringify 使用JSON.stringify序列化数据

var data = JSON.stringify({ 'ID': $scope.ID, 'ListPlayers': $scope.players, 'Team': $scope.team });

In your original code, you set a js object into the data to send. 在原始代码中,您将js对象设置为要发送的数据。 By serializing it, you send the data as json which your server can read. 通过序列化,您将数据作为json发送,服务器可以读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM