0

我正在使用带有 Razor2 的 ASP MVC4。我正在尝试使用 Javascript 来检索 JSON 数据并选择要显示的属性。每个线程都有自己的 JSON 文件,我一次显示 15 个线程。我无法一次获取所有数据,它会减慢页面加载时间。所以我认为客户端会很好,因为它不是敏感数据。

这是我的代码:

 public static PagedList<PiFDetailsModel> GetPagedThreads(int skip, int take)
    {
        using (var context = new PiFDbDataContext())
        {
            // refactor consideration...make this a pre-compiled query
            var threads = context.Threads
              .OrderBy(c => c.CreatedDate).Skip(skip).Take(take).ToList();

            var threadsCount = threads.Count();

            var details = new List<PiFDetailsModel>();
            foreach (Thread thread in threads)
            {
                var model = new PiFDetailsModel();

                var games = new List<Game>();
                // Make this AJAX instead.
                string text;
                try
                {
                    text = Utilities.GetThreadInfo(thread.ThingID)[0].data.children[0].data.selftext_html;
                    text = text.Replace("\n\n", "<br /><br />").Replace("\n", "<br />");
                }
                catch
                {
                    // TODO Handle exceptions better.
                    text = "Reddit is currently down or too busy, cannot retrieve information at this time";
                }

                foreach (ThreadGame game in thread.ThreadGames)
                {
                    if (games.Any(x => x.Name == game.Game.Name))
                    {
                        games.Find(x => x.Name == game.Game.Name).Count += 1;
                    }
                    else
                    {
                        var simpleGame = game.Game;
                        simpleGame.Count = 1;
                        games.Add(simpleGame);
                    }
                }

                model.Games = games;
                model.GameCount = thread.ThreadGames.Count;
                model.ThreadTitle = thread.Title;
                model.Username = thread.User.Username;
                model.CreatedDate = thread.CreatedDate;
                model.ThreadID = thread.ThingID;

              //  model.SelfText = new HtmlString(text);

                details.Add(model);
            }

            return new PagedList<PiFDetailsModel>
            {
                Entities = details,
                HasNext = skip + 10 < threadsCount,
                HasPrevious = skip > 0
            };
        }
    }

[OutputCache(Duration = 60 * 5)]
        public static dynamic GetThreadInfo(string thingID)
        {
            string uri = string.Format("http://www.reddit.com/{0}/.json", thingID);
            var connect = WebRequest.Create(new Uri(uri)) as HttpWebRequest;

            connect.UserAgent = "r/playitforward site by /u/sevenalive";

            // Do the actual connection
            WebResponse response = connect.GetResponse();

            string resp;
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                resp = reader.ReadToEnd();
            }

            return new JavaScriptSerializer().Deserialize<dynamic>(resp);
        }

指数:

@foreach (var item in Model)
{
    <div class="pif">
        <div class="left">
            <div class="title"><a href="/PiF/@item.ThreadID">@item.ThreadTitle</a></div>
            <div class="description">
                <div class="expandable">
                    <p>@item.SelfText</p>
                </div>
            </div>
            <div class="createdTime">
                <strong>@Html.TimeAgo(@item.CreatedDate)</strong>
            </div>
            <div class="createdBy">
                @if (item.Games.Count() == 1)
                {
                   @item.Games.Single().Name
                }
                else
                {
                    <text>@item.GameCount games</text>
                }
                being given by <a href="@string.Format("http://reddit.com/u/{0}", item.Username)">@item.Username</a>
            </div>
        </div>
        <div class="left">
            <ul class="games">
                      @foreach (var game in item.Games)
                      {
                          <li>
                              <a href="@game.StoreUrl" title="@game.Name">@game.Name</a> <span style="color:#b5b8be; font-weight:600">@string.Format("({0}P)", game.PointWorth)</span>
                              @if (game.Count > 1)
                              {
                                  <span style="color:#b5b8be; font-weight:600">(@game.Count copies)</span>
                              }
                          </li>
                      }
                  </ul>
        </div>
        <div class="clearBoth"></div>
    </div>
}

我尝试进行一些搜索,但找不到任何我正在寻找的示例。我认为 javascript,可能是 JQuery,将是最好的方法。我是 Web 开发的新手,因此非常感谢您提供详细的示例。整个代码库是开源的,我可以使用帮助,所以如果你想请叉!https://github.com/sevenalive/PlayItForward

4

1 回答 1

0
function GetSelfText(thingId) {
    $.getJSON("http://www.reddit.com/r/playitforward/comments/" + thingId + "/.json?jsonp=?", { id: thingId }, function (data) {
        var tempHtml = $('<div/>').html(data[0].data.children[0].data.selftext_html).text();
        $("#selfText-" + thingId).html(tempHtml);
    })
}

<div class="description" id="selfText-@item.ThreadID">
                        <script type="text/javascript">
                            $(document).ready(function () { GetSelfText('@item.ThreadID'); });
                        </script>
            </div>
于 2012-07-02T08:50:02.347 回答