John Schultz John Schultz - 1 year ago 86
ASP.NET (C#) Question

Dynamically populate a DropdownList based on another DropDownList's selection

I need to be able to populate a DropDownList based on the selection of a prior DropDownList.

I noticed there are allot of similar topics on SO, unfortunately, I need to do this with out using an AJAX call and needs to be done in MVC5 without doing a postback (If Possible).

  1. Is this even possible?

  2. Where do I begin? Is/Are there any examples I can go off of?

Answer Source

Actually it is possible to do it without AJAX but would still require some Javascript:

Both first and second dropdowns should have all the available options prerenderd. For each option on the second dropdown specify for what value of the first dropdown the option should be visible. For example:

<select id="firstDd">
   <option value="car">Cars</option>
   <option value="plane">Planes</option>
</select >

<select id="secondDd">
   <option value="ferrari" data-display-on="car">Ferrari</option>
   <option value="bugatti" data-display-on="car">Bugatti</option>
   <option value="747" data-display-on="plane">Boeing 747</option>
   <option value="757" data-display-on="plane">Boeing 757</option>
</select >

Now with some simple javascript you can toggle visibility of second dropdown options based on the value of first one:

  var value = $(this).val();
    var $secondDd = $('#secondDd');
    var $selectedOption = $('option:selected', $(this));
    $('option', $secondDd).hide();


Here is working JSFiDDLE that demonstrates this approach