C
C#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; }
(...)
P
pyrodistic558d 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.
A
Anton558d 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
P
pyrodistic558d 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?
A
Anton558d ago
[ApiController] applies some good defaults to a controller. Apply it to the controller class
P
pyrodistic558d ago
But is it okay for the controller to have that annotation even though only one method in it requires it?
A
Anton558d 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
P
pyrodistic558d ago
No problem, was just going to say that.
A
Anton558d 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
P
pyrodistic558d 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.
A
Anton558d 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
P
pyrodistic558d ago
Yeah, it should use the id as the property name as far as I'm aware. No problem, thank you for trying!
Want results from more Discord servers?
Add your server
More Posts
Assembly service findingHi, I am trying to find out if it's possible to get IServiceProvider, Microsoft IConfiguration or sohow do i submit a progra min vs to google classroomim trying to submit a project that's due to today but when i do submit it all i get is this and not WPF custom property not recognized by the compilerI have defined a custom property like below, it's in the namespace `CarApp`. It is supposed to repreEntity Framework DbContextOptionsBuilder.UseSqlServer() missing definitionI just installed the newest version of Entity Framework (6.0.9) and am inside my program.cs trying tDoes API manual nuget downloads come with the package dependencies?-WPF passing binding to a template from DataGridTemplateColumnSay, I have a template like this in resources, which I want to reuse for multiple columns, and whichBest way to implement a regex based lexer [Answered]In a regex lexer, you can loop over every pattern and do something like this: ```cs if (match.Successtring query in C Sharpi am trying to get values from 2 website links and assign them to a lable using visual studio one is there a convention for validating login sessions with MVC?Assuming I'm using ASP, ADO and .NET Say I want to construct a project to have several functions thUsing SQL db to create object ID or application?I have an application where my records in my DB need to have unique IDs. Should I leave this responsObject Initializers - To Parenthesize or Not To Parenthesize (that is the question)What is the difference between the object initializers on lines 1 and 2? In what situations should oHow do I move my mouse curser on screen?I went through most of stack overflow and some YouTube tutorials but didn't fins anythingHow do I move my mouse curser on screen?i was wondering if its possible to move the curse on the screen using c#SQL Error when trying to get an IDI'm trying to add username password and email to my users table And then get the ID of this new userEF Structuring ProblemBasically I have users that I want to assign to a group. But I also want the group to have a parent,data transfer between classesI want to list 'uname' value in method X, to method Y i am new to oopA generic and efficient way to feed in text for a lexer or scannerIn the past I was lazy and always just shoved a string into my lexical analyzer as input, but what'sBlazor Re-render [SOLVED]Hello, I have a property stored in static class, and I would like to re-render some components that Restarting audio with MediaPlayer?I've made a button that uses MediaPlayer to play a custom MP3 file that I've made. ```cs MediaPlayerWhat's the meaning of CS0659?```'class' overrides Object.Equals(object o) but does not override Object.GetHashCode()``` I got thi