Loading child dropdownlist based one selected value of parent dropdownlist - is very common requirement in web application development, you come across many situation when you need it, for example, loading cities based on country selected, loading students based one class or section selected etc.
In below example we learn exactly how to solve that problem in asp.net mvc application.
Here in the example of loading child dropdownlist depending on value change parent dropdownlist using jQuery
Step 1: Create two dropdownlist in your Asp.net page, one for country and one for state. Write below code in Razor view
@Html.DropDownListFor(m => m.CountryId, new SelectList(ViewBag.Countries, "Value", "Text"), "Select Country", new { data_url = Url.Action("GetStates") }) @Html.DropDownListFor(m => m.StateId, new SelectList(ViewBag.States, "Value", "Text"), "Select State")
Step 2: Write a method in controller which will return JsonResult of states, so that can be consumed using jquery , and populate the state list
public JsonResult GetStates(int countryId) { IEnumerable<tbState> states = _SecurityService.GetStates(countryId); return Json(states, JsonRequestBehavior.AllowGet); }
Step 3: now lets look at the script, where we get the JSON result and populate the state dropdownlist
<script> $(document).ready(function () { $('#CountryId').change(function () { var url = $(this).data('url'); var data = { countryId: $(this).val() }; $.getJSON(url, data, function (GetStates) { var ddlState = $('#StateId'); ddlState.empty(); ddlState.append($('<option/>', { value: 0, text: "Select State" })); $.each(GetStates, function (index, StateObj) { ddlState.append($('<option/>', { value: StateObj.StateId, text: StateObj.State })); }); }); }); }); </script>
Enjoy populating dropdownlist using jQuery in asp.net mvc
Make sure you have included right jquery reference in your page, because on-changed event call is made using jquery, so right jquery reference is required.