简体   繁体   English

返回JSON数据以查看ASP.NET MVC中的页面

[英]Returning JSON data to view page in ASP.NET MVC

I'm working on MVC project and i using jQuery in view page to get data from controller. 我正在MVC项目上,我在视图页面中使用jQuery从控制器获取数据。

public JsonResult CheckUpdate()
{
  dt = dt.AddSeconds(-100);

  IQueryable<Tweet> _tweet = ttr.CheckTime(dt);

  return Json(_tweet, JsonRequestBehavior.AllowGet);
}

This is a method in my controller which gets data back from the repository class and returns it as JSON to my view page, which uses jQuery to get it. 这是控制器中的一种方法,该方法从存储库类中获取数据并将其作为JSON返回给我的视图页面,该视图页面使用jQuery进行获取。

When i run program and inspect in Firebug, it shows me an error which is: 当我运行程序并在Firebug中检查时,它显示了一个错误,它是:

A circular reference was detected while serializing an object of type 'TweetTrafficReport.Models.User' 序列化类型为'TweetTrafficReport.Models.User'的对象时,检测到循环引用

My question is 我的问题是

  • Is it correct that i return JSON data which it is IQueryable type 我返回IQueryable类型的JSON数据是否正确
  • How can i use JSON data in my view page and not get an error like above 我如何在我的视图页面中使用JSON数据而不出现上述错误

Thanks for ur help :) 感谢您的帮助:)

You shouldn't really return IQueryable as Json, try returning a ViewModel instead 您不应该真正将IQueryable作为Json返回,而是尝试返回ViewModel

public JsonResult CheckUpdate()
{

   dt= dt.AddSeconds(-100);

   IQueryable<Tweet> _tweet = ttr.CheckTime(dt);

   var tweetVm = _tweet.Select(t => new TweetViewMode(){ Message = t.Message });

   return Json(tweetVm, JsonRequestBehavior.AllowGet);
}

The circular reference i bet is because of the fact you have your Tweet object reference inReplyTo 我打赌的循环引用是因为您在InReplyTo中拥有Tweet对象引用

IQueryable Really isnt as big an issue as casting each Tweet as a JsonCapableTweet like hanselman does http://nerddinnerbook.s3.amazonaws.com/Part11.htm 与hanselman一样,像将每个Tweet强制转换为JsonCapableTweet一样,IQueryable Really并不是一个大问题,就像http://nerddinnerbook.s3.amazonaws.com/Part11.htm

however it does help to lolok at the way Twitter does this 但是它确实有助于Twitter做到这一点

http://search.twitter.com/search.json?callback=foo&q=twitter http://search.twitter.com/search.json?callback=foo&q=twitter

thats pretty nice json they return, matching yours to theirs is a good habit to have 多数民众赞成在返回的json很好,将您的匹配到他们的是一个好习惯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM