按日期订购asp.net MVC 5 [英] Order by date asp.net MVC 5
本文介绍了按日期订购asp.net MVC 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个创建新闻条目并显示10条新闻的应用程序.它应该显示10个最新"新闻.现在,它显示了10个最古老的新闻.
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.
如何更改此设置.是否更改控制器,以便按日期对数据进行排序?还是可以在视图中做到?
控制器:
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.
这篇关于按日期订购asp.net MVC 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文