我有一个创建新闻条目并显示 10 条新闻的应用程序。它应该显示 10 条“最新”新闻。现在它显示 10 个最旧的新闻。
我该如何更改它......我是否更改控制器以便数据按日期排序?或者我可以在视图中执行吗?
控制器:
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);
}
最好在您的控制器中执行此操作:
public ActionResult Index()
{
return View(db.News.OrderByDescending(news => new.dateCreated).Take(10).ToList());
}
这样,您就可以从数据库中获取排序后的数据。一般来说,您应该尽可能保持视图“无代码”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)