gpt4 book ai didi

c# - 按日期排序 asp.net MVC 5

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:18 24 4
gpt4 key购买 nike

我有一个创建新闻条目并显示 10 条新闻的应用程序。它应该显示 10 个“最新”新闻。现在它显示 10 个最旧的新闻。

我如何更改它。我是否更改 Controller 以便数据按日期排序?或者我可以在 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);
}

最佳答案

最好在您的 Controller 中执行此操作:

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

这样,您就可以从数据库中对数据进行排序。通常,您应该尽可能保持 View “无代码”。

关于c# - 按日期排序 asp.net MVC 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22095694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com