2017-08-04 23 views
0

我有一个Web应用程序,用户可以在主页上发布项目。目前,主页上的项目从最早的日期到最新的日期列出。这不好,因为用户希望在访问主页时查看最近的帖子。如何列出帖子从最新到最旧在ASP.NET MVC5

我在我的发布模型中有一个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; } 
    } 

回答

0

使用db.Posts.OrderByDescending(p => p.DatePosted).ToList()

+0

不错。完美工作。 – Michael

+0

@Michael如果它解决了您的问题,请将其标记为答案。谢谢 – Shahzad

+0

我会的。当我试图接受答案时,它总是告诉我等待五分钟。 – Michael

相关问题