We just used a
SelectList to filter Continents on the list page. We can use a similar approach on the Country Edit page. We will replace the Continent
<input> text box with a
SelectList. This has the added value of ensuring that only a valid Continent is selected.
We fill the Continents select list from the EF context DBSet and specify the key and display value. This allows the user to see the full Continent name but the database will properly store the Continent ID:
Continents = new SelectList(_context.Continents, nameof(Continent.ID), nameof(Continent.Name));
<select> uses the
asp-for attribute the same way
<input> does. It has an additional
asp-items attribute for the source of the dropdown list:
<select asp-for="Country.ContinentID" asp-items="Model.Continents" class="form-control" ></select>
There is no need for validation since only values in the list are acceptable. We will remove the validation requirements from the Country model and rely on the
Open the file Pages/Countries/Edit.cshtml.cs and add a using statement for the select list:
Add a member property called
Continents to hold the
SelectList. Put this under the public Country declaration.
OnGetAsync(), fill the Continents select list from the EF context and specify the source DbSet, key, and display value as parameters.
Open the file Pages/Countries/Edit.cshtml and replace the
<input> tag and the validation
ContinentID with a
<select> tag. There is no need for validation since only values in the list are acceptable.
Open the file Models/Country.cs. Comment out the
[RegularExpression] annotations for
ContinentID. They are no longer needed.
Run the site and view the results in the browser. Edit a Country and see that the full name of the Continent displays. Change the Continent and click Save. Create a new Country and select your favorite Continent. Click Save.