user3265963 user3265963 - 2 months ago 29
C# Question

Order by date asp.net MVC 5

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

Answer

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.