简体   繁体   中英

Model from AngularJS to ASP.NET MVC5

I have some problems posting to my controller from 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..

Here are my 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:

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

This is my Angular code:

$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?

Thank you!!

Serialize your data with 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. By serializing it, you send the data as json which your server can read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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