How to Implement Cascading Dropdowns in ASP.NET MVC
Prerequisites:
- Knowledge of ASP.NET MVC.
- Knowledge of HTML.
- Knowledge of JavaScript.
- Knowledge of Bootstrap.
- Knowledge of JQuery.
- Knowledge of C# Programming.
Download Now!
2) Create suitable default layout for your project and include relevant JavaScripts and CSS styles libraries references. I am using Bootstrap-Select plugin for bootstrap 3.4.1 framework. Download this plugin for much rich interactive dropdown menu experience.
3) The data structure of a dropdown menu is value-text type list, where value can be associated with unique identification key (ID) and the text will be the end-user friendly display text. When user selects an item from the dropdown menu, the system will capture the related ID key of that item. For this type of scheme, create a ViewModel for both dropdown menus with ID selection as property. As shown in below lines of code i.e.
...
/// <summary>
/// Select country ID property
/// </summary>
[Display(Name = "Choose country")]
public int? SelectedCountryId { get; set; }
/// <summary>
/// Select state ID property
/// </summary>
[Display(Name = "Choose state")]
public int? SelectedStateId { get; set; }
...
...
<div class="row">
<div class="col-xs-4 col-xs-push-2">
<div class="form-group">
@Html.DropDownListFor(m => m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new { id = "CountryList", @class = "selectCountry show-tick form-control" })
</div>
</div>
<div class="col-xs-4 col-xs-push-2">
<div class="form-group">
@Html.DropDownListFor(m => m.SelectedStateId, this.ViewBag.StateList as SelectList, new { id = "StateList", @class = "selectState show-tick form-control" })
</div>
</div>
</div>
...
...
$('.selectCountry').on('change',
function ()
{
// Initialization
var countryId = $('option:selected', $(this)).val();
// Loading States List.
$.ajax({
url: '/Home/GetStates',
type: "GET",
dataType: "JSON",
data: { countryId: countryId },
success: function (result)
{
$('#StateList').html(""); // clear before appending new list
var items = '';
$.each(result, function (i, data)
{
$('#StateList').append($('<option></option>').val(data.Value).html(data.Text));
});
// Refresh.
$('#StateList').selectpicker('refresh');
}
});
});
...
7) Now, when you execute your project, you will be able to see multiple dropdown menus bind with each other in action as shown below i.e.

