C
C#2y 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>
<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; }
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; }
(...)
11 Replies
pyrodistic
pyrodistic2y ago
On the view:
@section Scripts
{
<script>
$(function () {
$("#SelectedTaxonomyId").change(function () {
var v = $(this).val();
var url = $("#SelectedSpeciesId").data("url") + '?taxonomyId=' + v;
var $states = $("#SelectedSpeciesId");
$.getJSON(url, function (states) {
$states.empty();
$.each(states, function (i, item) {
$states.append($("<option>").text(item.Text).val(item.Value));
});
});
});
});
</script>
}

@Html.DropDownListFor(a=>a.SelectedTaxonomyId,Model.ListTaxonomy,"Select one")
@Html.DropDownListFor(a => a.SelectedSpeciesId, Model.ListSpecies, "Select one", new { data_url = Url.Action("GetStates") })
@section Scripts
{
<script>
$(function () {
$("#SelectedTaxonomyId").change(function () {
var v = $(this).val();
var url = $("#SelectedSpeciesId").data("url") + '?taxonomyId=' + v;
var $states = $("#SelectedSpeciesId");
$.getJSON(url, function (states) {
$states.empty();
$.each(states, function (i, item) {
$states.append($("<option>").text(item.Text).val(item.Value));
});
});
});
});
</script>
}

@Html.DropDownListFor(a=>a.SelectedTaxonomyId,Model.ListTaxonomy,"Select one")
@Html.DropDownListFor(a => a.SelectedSpeciesId, Model.ListSpecies, "Select one", new { data_url = Url.Action("GetStates") })
On the Controller:
public IActionResult Create(int id)
{
var model = new PetViewModel();
model.ListTaxonomy = _petRepository.GetTaxonomies();
return View(model);
}

public List<SelectListItem> GetTaxonomies()
{
var list = new List<SelectListItem>();
foreach (var item in _context.Taxonomy)
{
list.Add(
new SelectListItem() { Value = item.Id.ToString(), Text = item.Name }
);
}
return list;
}
public IActionResult Create(int id)
{
var model = new PetViewModel();
model.ListTaxonomy = _petRepository.GetTaxonomies();
return View(model);
}

public List<SelectListItem> GetTaxonomies()
{
var list = new List<SelectListItem>();
foreach (var item in _context.Taxonomy)
{
list.Add(
new SelectListItem() { Value = item.Id.ToString(), Text = item.Name }
);
}
return list;
}
I tried to implement the next and final step according to the SO post by adding to the controller:
public ActionResult GetStates(int taxonomyId)
{
var states = new List<SelectListItem>();
if (taxonomyId == 1)
{
states.Add(new SelectListItem() { Value = "101", Text = "Michigan" });
states.Add(new SelectListItem() { Value = "102", Text = "New York" });
}
return Json(states, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
public ActionResult GetStates(int taxonomyId)
{
var states = new List<SelectListItem>();
if (taxonomyId == 1)
{
states.Add(new SelectListItem() { Value = "101", Text = "Michigan" });
states.Add(new SelectListItem() { Value = "102", Text = "New York" });
}
return Json(states, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
But it obviously doesn't work. And I'm not sure where that method is even supposed to go to or how it's actually being referenced in any way... I think I'm missing something pretty basic, some knowledge that I just never got and I could use some help please. Thanks in advance.
Anton
Anton2y ago
You need [ApiController] on the controller and [HttpGet] or [HttpPost] on the methods, and your controller needs to be registered in the main method
pyrodistic
pyrodistic2y ago
Hello, sorry could you explain it a but further? On the Pet Controller my GET Create method has the [HttpGet] and so POST also has the correct tag (sorry not displaying it). The GetStates method should have the [ApiController] tag? Should it be in a different controller altogether?
Anton
Anton2y ago
[ApiController] applies some good defaults to a controller. Apply it to the controller class
pyrodistic
pyrodistic2y ago
But is it okay for the controller to have that annotation even though only one method in it requires it?
Anton
Anton2y ago
does it serve html or act as an api endpoint? if it's an endpoint, you should always apply that it's not required but it's a good thing to always use ah yes, it does render view I didn't notice that, sorry
pyrodistic
pyrodistic2y ago
No problem, was just going to say that.
Anton
Anton2y ago
I don't know, I can't say what the heck is wrong without debugging this, but frankly, the code is quite a mess It's hard to say what's wrong at a glance
pyrodistic
pyrodistic2y ago
It's pretty much all copy paste from the SO post. Just changed the names. My main doubts are: is the JS correctly located inside the section and tags <script>? Where is it expected for the ActionResult GetStates to reside? I've barely ever used JS so I'm not really fully understanding the implementation.
Anton
Anton2y ago
hold up, do elements with those ids exist? SelectedTaxonomyId and ehatnot. you might've forgotten to rename those it seems like they are generated in the @Html things I'm sorry, I can't help you with razor, I haven't really used it
pyrodistic
pyrodistic2y ago
Yeah, it should use the id as the property name as far as I'm aware. No problem, thank you for trying!