Therefore, this code results in a single query that's not executed until the return View statement. The query isn't executed until you convert the IQueryable object into a collection by calling a method such as ToListAsync. When you create and modify IQueryable variables, no query is sent to the database. The code creates an IQueryable variable before the switch statement, modifies it in the switch statement, and calls the ToListAsync method after the switch statement. The method uses LINQ to Entities to specify the column to sort by. These two statements enable the view to set the column heading hyperlinks as follows: Current sort order The first one specifies that if the sortOrder parameter is null or empty, NameSortParm should be set to "name_desc" otherwise, it should be set to an empty string. public async Task Index(string sortOrder) The two ViewData elements (NameSortParm and DateSortParm) are used by the view to configure the column heading hyperlinks with the appropriate query string values. When the user clicks a column heading hyperlink, the appropriate sortOrder value is provided in the query string. The students are displayed in ascending order by last name, which is the default as established by the fall-through case in the switch statement. The first time the Index page is requested, there's no query string. The parameter will be a string that's either "Name" or "Date", optionally followed by an underscore and the string "desc" to specify descending order. The query string value is provided by ASP.NET Core MVC as a parameter to the action method. This code receives a sortOrder parameter from the query string in the URL. Return View(await students.AsNoTracking().ToListAsync()) Students = students.OrderBy(s => s.LastName) Students = students.OrderByDescending(s => s.EnrollmentDate) Students = students.OrderBy(s => s.EnrollmentDate) Students = students.OrderByDescending(s => s.LastName) Var students = from s in _context.Students ViewData = sortOrder = "Date" ? "date_desc" : "Date" ViewData = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "" In StudentsController.cs, replace the Index method with the following code: public async Task Index(string sortOrder) Add sorting Functionality to the Index method To add sorting to the Student Index page, you'll change the Index method of the Students controller and add code to the Student Index view.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |