Reputation: 672
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).
Upvotes: 1
Views: 4424
Reputation: 8781
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:
$('#firstDd').change(function(){
var value = $(this).val();
if(value)
{
var $secondDd = $('#secondDd');
var $selectedOption = $('option:selected', $(this));
$('option', $secondDd).hide();
$('option[data-display-on="'+value+'"]',$secondDd).show();
}
$($secondDd).val(null);
})
$('#firstDd').change();
Here is working JSFiDDLE that demonstrates this approach
Upvotes: 4