Ian
Ian

Reputation: 27

How does the following EF MVC 5 code for sorting work?

https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

public ActionResult Index(string sortOrder){


   ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
   ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
   var students = from s in db.Students
                  select s;
   switch (sortOrder)
   {
      case "name_desc":
         students = students.OrderByDescending(s => s.LastName);
         break;
      case "Date":
         students = students.OrderBy(s => s.EnrollmentDate);
         break;
      case "date_desc":
         students = students.OrderByDescending(s => s.EnrollmentDate);
         break;
      default:
         students = students.OrderBy(s => s.LastName);
         break;
   }
   return View(students.ToList());
}
  1. The ternary operators merely return one of the results based on the condition, they do not change sortOrder right?
  2. If sortOrder is "Date" then the code sets the ViewBag.DateSortParm to "date_desc" but isn't sortOrder still "Date" so it won't actually change the order?

I don't see how it is possible for this code to work correctly but it does.

Upvotes: 1

Views: 85

Answers (1)

ADyson
ADyson

Reputation: 61925

1) The ternary operators just set a ViewBag value, yes. They don't alter the content of the sortOrder variable. In fact quite the opposite - they decide what to do based on the value of sortOrder.

2) You're right it doesn't have any effect on the way students actually gets sorted, which is determined by the switch statement.

The reason the ViewBag parameter values are set to the opposite of what you might expect are because in the View they are used to build hyperlinks which, when clicked, will cause the data to be sorted the opposite way to what it is now. e.g. if currently sorting "Date" (Date ascending), then it will construct a link which, if clicked, will pass back an instruction to the server to re-sort and return the data, but this time sorted by "date_desc" (Date descending) instead. So it does make sense, if you take into account what those values are used for later on.

Upvotes: 2

Related Questions