【发布时间】:2015-03-15 04:47:34
【问题描述】:
在我的 ASP.NET Web 窗体应用程序(使用代码优先的 EF 和 Web Api)中,我需要使用 ajax 读取项目列表 (List<Post>) 并使用以下代码填充帖子列表。但是,我遇到了一个奇怪的问题,如下所述。
function LoadPostsByTimeframe(currTimeframeId) {
jQuery.support.cors = true;
$.ajax({
url: '/api/post/GetPostsByTimeframe?tfId=' + currTimeframeId,
type: 'GET',
contentType: "application/json; charset=utf-8;",
dataType: 'json',
success: function (response) {
var posts = response.d;
//do stuff
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
}
在我的控制器类中,当我使用以下方法检索项目列表时:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public IList<Post> GetPostsByTimeframe(int tfId)
{
gEchoLuDBContext db = new gEchoLuDBContext();
var posts = db.Posts.Where(p=>p.TimeFrameId == tfId).ToList();
return posts;
}
我得到了正确的每一个项目(第三个不适合碎石)
但是,我需要检索每个项目的相关人员数据。因此,我需要使用以下代码(带有Include)来检索项目。
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public IList<Post> GetPostsByTimeframe(int tfId)
{
gEchoLuDBContext db = new gEchoLuDBContext();
var posts = db.Posts.Include(po=>po.Person).Where(p=>p.TimeFrameId == tfId).ToList();
return posts;
}
我有这个输出(只返回第一项,其他两项为空):
在这两种情况下(无论是否包含),Controller 方法都会返回一个包含所有项目的有效List<Post>。但是,对于 Include 版本,列表值(第一个值除外)不会显示在 ajax/jquery 端。
你认为我遗漏了什么吗?
【问题讨论】:
标签: c# asp.net ajax entity-framework asp.net-web-api