【发布时间】:2015-10-25 16:58:18
【问题描述】:
我一直在尝试使用 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; }
}
【问题讨论】:
-
如果你返回一个列表
那么它工作得好吗?你的意思是代替 list ? -
@LiranBo;没错,控制台日志显示
{ [aa],[bb] }. but not when i return JSON data withList` -
你可以发布你的问题类
-
@LiranBo:我也添加了实体
-
为了安全起见,您是否调试并检查过
List<Question> posts = PostRepository.Posts(10);不返回 null 或空列表?因为这看起来像一个 json 错误,而不是其他任何东西,因为你说常规的字符串列表有效。
标签: c# angularjs asp.net-mvc service controller