AngularJS服务控制器记录自定义类集合的未定义错误

时间:2015-10-25 06:51:14

标签: c# angularjs asp.net-mvc service controller

我一直在尝试用ASP.NET MVC实现AngularJS,我遇到了奇怪的问题。我已使用$http.get()请求自定义类列表Question,但它会转到角度控制器的错误块。

当我返回List<sting>时,它运行良好,并且不记录任何错误并在UI上显示。

这是我的代码:

AngularJS:

var BlogPostApp = angular.module('BlogPostApp', [])

BlogPostApp.controller('BlogPostController', function ($scope, BlogPostService) {
    getPosts();
    function getPosts() {
        BlogPostService.getPosts()
            .success(function (posts) {
                $scope.posts = posts;
                console.log($scope.posts);
            })
            .error(function (error) {
                $scope.status = 'Unable to load blog post data: ' + error.message;
                console.log($scope.status);
            });
    }
});

// Services
BlogPostApp.factory('BlogPostService', ['$http', function ($http) {
    var BlogPostService = {};
    BlogPostService.getPosts = function () {
        return $http.get('/Editor/GetPosts');
    };
    return BlogPostService;
}]);

MVC代码

当我尝试返回List<Question>时,它会记录未定义的错误

public JsonResult GetPosts()
        {
            List<Question> posts = PostRepository.Posts(10);
            return Json(posts, JsonRequestBehavior.AllowGet);
        }

List<string>

一起使用
public JsonResult GetPosts()
        {
            List<string> lst = new List<string>();
            lst.Add("aa"); 
            lst.Add("bb");
            return Json(lst, JsonRequestBehavior.AllowGet);
        }

实体类:

public partial class Question
    {
        PIdbEntities db = null;
        public Question()
        {
            this.QAMaps = new HashSet<QAMap>();
            db = new PIdbEntities();
        }
        public int Id { get;set; }
        public string Text { get; set; }
        public string Html { get; set; }
        public string Code { get; set; }
        public string Title { get; set; }
        public string ShortDescription { get; set; }
        public System.DateTime PostedOn { get; set; }
        public Nullable<System.DateTime> ModifiedOn { get; set; }
        public string Meta { get; set; }
        public string UrlSlug { get; set; }
        public bool IsPublished { get; set; }
        public int UserId { get; set; }

        public virtual ICollection<QAMap> QAMaps { get; set; }
        public IList<Answer> Answers { get; set; }
    }

1 个答案:

答案 0 :(得分:1)

问题在于JSON格式。你的问题有一个自我引用循环(问题 - &gt;回答 - 再次问题)。

因此,JSON序列化程序面临无限循环,要修复它,您可以使用[JsonIgnore]属性,不要忘记添加using Newtonsoft.Json;

将此[JsonIgnore]属性相应地添加到任一模型(问题\答案):

[JsonIgnore]
public IList<Answer> Answers { get; set; }

Answer实体中的更好选项,将该属性添加到Question导航属性。

通过这种方式,您将获得问题的答案集,并且您无法获得自我参考循环。