Order by date asp.net MVC 5

ぐ巨炮叔叔 提交于 2019-12-24 17:38:25

问题


I have a application that creates News Entries and displays 10 news. It should display the 10 "newest" news. As it is now it display the 10 oldest news.

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);
        }

回答1:


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.




回答2:


Use the below code to display 10 latest news:

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



回答3:


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>
}


来源:https://stackoverflow.com/questions/22095694/order-by-date-asp-net-mvc-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!