【问题标题】:How To List Posts From Newest To Oldest In ASP.NET MVC5如何在 ASP.NET MVC5 中列出从最新到最旧的帖子
【发布时间】:2018-01-12 16:40:00
【问题描述】:

我有一个网络应用程序,用户可以在其中在主页上发布项目。目前,主页上的项目是从最早到最新列出的。这不好,因为用户希望在访问主页时看到最新的帖子。

我的帖子模型中有一个 DatePosted 属性,用于跟踪发布的时间和日期。如何使用该属性按最新到最旧进行排序?

这是我的操作,它将用户带到他们可以看到帖子的主页:

// GET: Posts
public ActionResult Index()
{
    var posts = db.Posts.ToList();

    return View(posts);
}

观点:

@model IEnumerable<DothanTrader.Models.Post>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}



@{
    int i = 5;
}
<div class="row">
    @foreach (var item in Model)
    {
        if (i == 5)
        {
            @:</div><div class="row">

            i = 1;
        }
        <div class="col-md-3">
            <div class="panel panel-default">
                <div class="panel-heading">
                    @Html.ActionLink(@item.Title, "Details", "Post", new { id = item.PostId }, null) 
                </div>
                <div class="panel-body" style="min-height: 200px; max-height: 200px; ">
                    <img src="@Url.Content("~/Content/images/" + System.IO.Path.GetFileName(item.Image))" alt="" class="img-responsive" />
                </div>
                <div class="panel-footer">
                    <span class="glyphicon glyphicon-eye-open"> @item.Views</span> | <span class="glyphicon glyphicon-usd"> @item.Price</span>
                    <div class="pull-right">
                        <span>@item.DatePosted.Value.ToShortDateString()</span> 
                    </div>
                </div>
            </div>
        </div>
        { i++; }
    }
</div>

模型(以备不时之需):

public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime? DatePosted { get; set; }
        public string Image { get; set; }
        public float Price { get; set; }
        public int  Views { get; set; }
        public int Likes { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
        public string ApplicationUserId { get; set; }
    }

【问题讨论】:

    标签: asp.net asp.net-mvc entity-framework razor


    【解决方案1】:

    使用db.Posts.OrderByDescending(p =&gt; p.DatePosted).ToList()

    【讨论】:

    • 不错。完美运行。
    • @Michael 如果它解决了您的问题,请将此标记为答案。谢谢
    • 我会的。当我尝试接受答案时,它一直告诉我等待五分钟。
    • @Jonathan 感谢您的提醒。我之前使用手机上的应用程序接受了它,但我猜它不喜欢它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多