C# 使用匿名类型时,匿名类型中包含的List对象在ajax中返回null
我的代码优先实体框架应用程序中有一个奇怪的问题。通常,如果我有下面的代码,我可以得到一个特定的帖子,附带在ajax中正确关联的评论C# 使用匿名类型时,匿名类型中包含的List对象在ajax中返回null,c#,asp.net,ajax,entity-framework,C#,Asp.net,Ajax,Entity Framework,我的代码优先实体框架应用程序中有一个奇怪的问题。通常,如果我有下面的代码,我可以得到一个特定的帖子,附带在ajax中正确关联的评论 gEchoLuDBContext db = new gEchoLuDBContext(); var post= db.Posts.Include(po=>po.CommentsAssociated).Include(po => po.Person) .Single(p => p.PostId
gEchoLuDBContext db = new gEchoLuDBContext();
var post= db.Posts.Include(po=>po.CommentsAssociated).Include(po => po.Person)
.Single(p => p.PostId == postId)
.AsNoTracking();
但是,如果我不得不使用下面的代码,那么ajax中的CommentsAssociated就没有任何价值
gEchoLuDBContext db = new gEchoLuDBContext();
IEnumerable<Post> post = db.Posts.Where(p => p.PostId == postId)
.Include(p => p.Person)
.Include(p => p.CommentsAssociated)
.Include(p => p.PostBookmarks)
.Include(p => p.PostLikes)
.ToList().Select(p => new Post
{
PostId = p.PostId,
Title = p.Title,
Content = p.Content,
DatePosted = p.DatePosted,
Person = p.Person,
CommentsAssociated = p.CommentsAssociated,
IsLikedByCurrentUser = p.PostLikes.Select(pl => pl.UserId).Contains(User.Identity.GetUserId()),
IsBookmarkedByCurrentUser = p.PostBookmarks.Select(pb => pb.BookmarkedBy).Contains(User.Identity.GetUserId()),
NoOfComments = p.CommentsAssociated.Count()
});
var returnpost = post.FirstOrDefault();
return returnpost;
更新
当我序列化控制器中的post对象并返回它时:
string json = JsonConvert.SerializeObject(post, Formatting.Indented, serializerSettings);
我仍然存在与下图所示相同的win json字符串格式问题:
您是否正在以Json格式发送服务器返回的值?从上面的代码看,您似乎只是返回了服务器对象。@Dinesh我尝试过了,仍然是相同的问题,请查看更新。
$.ajax({
url: '/api/post/GetPostWithFullDetails?postId=' + postId,
type: 'GET',
contentType: "application/json; charset=utf-8;",
dataType: 'json',
success: function (post) {
$("#pnl_DisplayPostDetails.posttitle").html(post.Title);
$("#pnl_DisplayPostDetails.postcontent").html(post.Content);
if (post.CommentsAssociated.length) {
//other code
string json = JsonConvert.SerializeObject(post, Formatting.Indented, serializerSettings);