使用AngularJS post将对象列表传递给MVC操作方法

时间:2016-11-10 12:12:50

标签: angularjs asp.net-mvc

我有一个动作方法,如下所示:

[HttpPost]
    public ActionResult Ask(Question question)
    {
        if (ModelState.IsValid)
        {
            TempData["NewQuestion"] = question;
            return RedirectToAction("Submit");
        }
        return View(question);
    }

Question类定义如下:

public class Question    
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public string UserId { get; set; }
    public List<Tag> Tags { get; set; }
    public int Votes { get; set; }
    public List<Answer> Answers { get; set; }
    public int Views { get; set; }
    public DateTime CreationDate { get; set; }
}

我编写的用于调用上述给定操作方法的代码如下所示:

<script>
        function questionController($scope, $http) {            
            $scope.submit = function () {                
                var data = $.param({
                    Title: $scope.title,
                    Body: $scope.body,
                    Tags: [$.param({ TagName: 'MVC' }), $.param({ TagName: 'WCF' })]
                });
                var config = {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                    }
                };
                $http.post('Ask', data, config)
                    .success(function (data, status, headers, config) {
                        $scope.PostDataResponse = data;
                    })
                    .error(function (data, status, header, config) {
                        alert(data);
                    });
                };
        }
        var queApp = angular.module("queApp", []);
        queApp.controller("queCtrl", questionController);
    </script>

正在调用操作方法,但作为列表的Tags成员将被收到null。请让我知道我做错了什么。

1 个答案:

答案 0 :(得分:2)

尝试将Content-Type值更改为application/json

<script>
    function questionController($scope, $http) {            
        $scope.submit = function () {                
            var data =  {
                Title: $scope.title,
                Body: $scope.body,
                Tags: [{ TagName: 'MVC' }, { TagName: 'WCF' }]
            };
            var config = {
                headers: {
                    'Content-Type': 'application/json;charset=utf-8;'
                }
            };
            $http.post('Ask', data, config)
                .success(function (data, status, headers, config) {
                    $scope.PostDataResponse = data;
                })
                .error(function (data, status, header, config) {
                    alert(data);
                });
            };
    }
    var queApp = angular.module("queApp", []);
    queApp.controller("queCtrl", questionController);
</script>