Look at the types involved:
ViewBag.CountryList
is assigned to the value returned by
GetCountryList()
.
GetCountryList
returns a
IEnumerable<SelectListItem>
.
Your view attempts to cast
ViewBag.CountryList
to a
SelectList
using the
as
operator. This will return
null
, because the value isn't a
SelectList
. There is no conversion between
IEnumerable<SelectListItem>
and
SelectList
.
Change your view to specify the correct type, and use a cast instead of
as
so you'll get a better error message if the cast fails:
@Html.DropDownListFor(m => m.SelectedCountryId, (IEnumerable<SelectListItem>)ViewBag.CountryList, new { @class = "form-control" })
Type-testing and cast operators - C# reference | Microsoft Docs[
^]
SelectList Class (System.Web.Mvc) | Microsoft Docs[
^]
SelectExtensions.DropDownListFor Method (System.Web.Mvc.Html) | Microsoft Docs[
^]