Searching is now working. Let’s add sorting as well. We will use a <select>
tag to hold the column names in a series of <option>
tags. This will be linked to a member property that tracks the current sort column. We will add an onChange()
event that posts the form each time a change is made:
<select class="p-2" asp-for="SortField" onchange="this.form.submit();"> <option value="ID">Code</option> <option value="ContinentID">Cont</option> <option value="Name">Name</option> </select>
The LINQ query can be modified multiple times before it is evaluated. Sorting is managed by the OrderBy()
clause. A switch statement determines which column name to include in the LINQ query:
switch (SortField) { case "ID": countries = countries.OrderBy(c => c.ID); break; case "Name": countries = countries.OrderBy(c => c.Name); break; case "ContinentID": countries = countries.OrderBy(c => c.ContinentID); break; }
Instructions
Open the file Pages/Countries/Index.cshtml.cs. Add another using statement for the SelectList component.
- Microsoft.AspNetCore.Mvc.Rendering
Add a public string
property named SortField
with a default of "Name"
. This will need a [BindProperty]
that supports Get so the choice returns to the server when the <form>
does a post back.
Before the line that sets the Countries
property…
Countries = await countries.ToListAsync();
…add a switch
statement that sorts the countries
query based on SortField
. Expect Sortfield
to be one of three values:
"ID"
"Name"
"ContinentID"
Open the file Pages/Countries/Index.cshtml. After the <input>
tag for submitting, add a <label>
and the <select>
tag with a series of <option>
tags with field names:
<label asp-for="SortField" class="control-label"> Sort by: </label> <select class="p-2" asp-for="SortField" onchange="this.form.submit();"> <option value="ID"> Code </option> <option value="ContinentID"> Cont </option> <option value="Name"> Name </option> </select>
Note that onchange()
fires each time the dropdown value changes. The short JavaScript statement causes the <form>
to complete a post back. This reloads the page with OnGetAsync()
which in turn adds the OrderBy()
LINQ query modifier with the selected SortField
.