C#C
C#4y ago
pyrodistic

Cascading DropDown

I'm using MVC (.NET5) with EF and had this code to select a species on a View (to Create/Edit):
<b><label asp-for="Species" class="control-label"></label></b>
@Html.DropDownList("SpeciesId", new SelectList((System.Collections.IEnumerable) ViewData["Species"], "Id", "Name"), "Select Species", new { @class="form-control" })
<span asp-validation-for="SpeciesId" class="text-danger"></span>

It displayed every species but I wanted to have another drop down list that displays the taxonomy or class of a species, for example Mammal, and then filters what the species drop down displays. For example if Mammal is selected (id/index == 1, for example) in the taxonomy list, then the species list will only display the options that have that matching foreign key.

After spending pretty much all day trying to find a good explanation I'm a bit defeated. I was trying to follow https://stackoverflow.com/questions/46954959/how-to-create-cascading-drop-down-list , but unfortunately it doesn't seem to convey a deep enough explanation to me.

I have only a basic understanding of JS, and this is the first time using jQuery/AJAX.

I have on the PetViewModel class:
        public PetViewModel()
        {
            ListTaxonomy = new List<SelectListItem>();
            ListSpecies = new List<SelectListItem>();
        }

        public List<SelectListItem> ListTaxonomy { get; set; }
        public List<SelectListItem> ListSpecies { get; set; }

        public int SelectedTaxonomyId { get; set; }
        public int SelectedSpeciesId { get; set; }

(...)
Was this page helpful?