如何在ASP.NET MVC5中列出从最新到最旧的帖子

时间:2017-08-04 16:50:02

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

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

我的帖子模型中有一个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; }
    }

1 个答案:

答案 0 :(得分:0)

使用res.size