This can be done in many ways. One way is to force the server to return a filtered list of valid parameters via Ajax when the first drop-down menu changes.
For example, suppose this scenario is: a view with two DropDownLists; one with countries, and the other with states. The DropDownList with states is empty and is disabled by default until a country is selected.
So you can have this action in your controller:
public ActionResult Index() { ViewBag.Country = new [] { new SelectListItem() { Text = "Venezuela", Value = "1" }, new SelectListItem() { Text = "United States", Value = "2" } }; return View(); }
And this view:
<div class="editor-field"> @Html.DropDownList("Country") @Html.DropDownList("State", Enumerable.Empty<SelectListItem>(), "States", new { @disabled = "disabled" }) </div>
Now add the POST action to the controller. It receives the identifier of the selected country and returns a JSON containing a filtered list of states:
[HttpPost] public ActionResult StatesByCountry(int countryId) {
The last thing is client-side code. This example uses jQuery and sets up a listener for change events in the drop-down list of the country, which triggers a new controller action through Ajax. It then uses the return values ββto update the "State" DropDownList.
$(document).ready(function () { $('#Country').change(function () { $.ajax({ url: '/Home/StatesByCountry', type: 'POST', data: { countryId: $(this).val() }, datatype: 'json', success: function (data) { var options = ''; $.each(data, function () { options += '<option value="' + this.id + '">' + this.state + '</option>'; }); $('#State').prop('disabled', false).html(options); } }); }); });
source share