简体   繁体   English

按日期排序asp.net MVC 5

[英]Order by date asp.net MVC 5

I have a application that creates News Entries and displays 10 news. 我有一个创建新闻条目并显示10条新闻的应用程序。 It should display the 10 "newest" news. 它应该显示10个“最新”新闻。 As it is now it display the 10 oldest news. 现在,它显示了10个最古老的新闻。

How can I change that.. Do I change the controller so that the data is sorted by date? 我该如何更改。是否更改控制器,以便按日期对数据进行排序? Or can I do it in the view? 还是可以在视图中做到这一点?

Controller: 控制器:

public ActionResult Index()
        {
            return View(db.News.ToList());
        }

 // GET: /Newss/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Newss/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="ID,title,body,category,dateCreated")] News news)
        {
            if (ModelState.IsValid)
            {
                news.dateCreated = DateTime.Now;
                db.News.Add(news);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(news);
        }

It's best to do this in your controller: 最好在您的控制器中执行此操作:

public ActionResult Index()
{
    return View(db.News.OrderByDescending(news => new.dateCreated).Take(10).ToList());
}

This way, you get the data sorted from the DB. 这样,您可以从数据库中获得排序的数据。 In general, you should probably keep the view as 'codeless' as possible. 通常,您应该尽可能将视图保持为“无代码”。

Use the below code to display 10 latest news: 使用以下代码显示10条最新新闻:

public ActionResult Index()
{
return View(db.News.OrderByDescending(news => new.dateCreated).Take(10).ToList());
}

The above answers are great and work on the controller side. 上面的答案很好,并且可以在控制器端工作。 If you, for whatever reason, wanted to do it in the view, this is how it's done: 如果您出于某种原因想要在视图中执行此操作,请按以下步骤操作:

Ordering Model in View 视图中的订购模型

@foreach (var item in Model.OrderBy(item => item.PostedDate))
{
   <tr>
     <td>
        @Html.DisplayFor(modelItem => item.Id)
     </td>
     <td>
        @Html.DisplayFor(modelItem => item.PostedDate)
     </td>
     <td>
        @Html.DisplayFor(modelItem => item.SomethingAmazing)
     </td>
   </tr>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM