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 に答える