Learn

We now have a simple way of searching and sorting our countries. We might also want to limit our searches by continent. We can accomplish this with another select list.

LINQ is used to gather all continents while sorting then alphabetically:

IQueryable<string> continentQuery = from c in _context.Continents orderby c.ID select c.ID;

The result of the query is assigned to a SelectList component during OnGetAsync(). The component adds the All option as part of the markup.

We use another LINQ query modifier that checks for a selected continent and adds that condition. Multiple modifiers allows us to filter by a continent and include a country name search string:

if (!string.IsNullOrEmpty(SelectedContinent)) { countries = countries.Where(c => c.ContinentID == SelectedContinent); }

Instructions

1.

Open the file Pages/Countries/Index.cshtml.cs. Add properties for the selectlist contents and the current selection. The selectedContinent will need a [BindProperty] that supports Get so the choice returns to the server when clicking the Search submit button.

2.

Add a new LINQ query to get all the continent IDs sorted by ID. This goes inside the OnGetAsync() method above the Countries = statement.

3.

Return the query to the SelectList each time the page does a get.

4.

Add another modifier to the country LINQ query that checks for a selected continent and adds that condition. Note that multiple LINQ query modifiers are supported. In our case, that means we filter by a continent and include a country name search string.

5.

Open the file Pages/Countries/index.cshtml. Add a <label> and <select> tag to the header as the first item in the <form>. This goes above the SearchString <label>:

<label asp-for="SelectedContinent" class="control-label"> Continent: </label> <select class="p-2" asp-for="SelectedContinent" asp-items="Model.Continents" onchange="this.form.submit();"> <option value="">All</option> </select>

Run the site and view the results in the browser. Select Countries from the top nav bar. Pick a continent from the select list and click Search. Try doing a continent and a search string to see both work at the same time.

Sign up to start coding

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?