Home » Jquery » javascript – How do I populate a dropdown menu based on the user selection in a different dropdown menu in ASP.NET Core MVC?-Exceptionshub

javascript – How do I populate a dropdown menu based on the user selection in a different dropdown menu in ASP.NET Core MVC?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

For example:

Dropdown A lists animal types: mammals, reptiles, fish.
Then dropdown B would list animals available for a selected type.
If you select mammals then dropdown B would show: cat, dog, horse.

This is known as a conditional dropdown or cascading dropdown.

How to&Answer:

So I’ve learned that dynamic behaviour, in the sense of interacting with the server without reloading the page, requires the use of javascript. Here’s my solution which was cobbled together from multiple examples and tutorials:

Model:

public class MyModel
{
  public string IndependentProperty { get; set; }
  public string DependentProperty { get; set; }
}

ViewModel:

public class MyViewModel
{
  public MyModel Model { get; set; }
  public IEnumerable<SelectListItem> IndependentOptions { get; set; }
}

View:

@using MyViewModel

<form method="post">
  <select id="independentOption"
    asp-for="Model.IndependentProperty"
    asp-items="Model.IndependentOptions"
    onchange="updateDependentOptions()">
    <option value="" selected="true">Select</option>
  </select>

  <select id="dependentOption"
    asp-for="Model.DependentProperty">
    <option value="" selected="true">Select</option>
  </select>
</form>

<script type="text/javascript">
  function updateDependentOptions() {  
    var independentOption = $('#independentOption').val();

    ajaxCall(
      '/MyController/GetDependentOptions?independentOption=', 
      independentOption
    ).done(
      function (response) {
        $('#dependentOption').empty();

        if (response.length > 0) {
          var options = '';

          for (var i = 0; i < response.length; i++) {
            options += '<option value="' 
              + response[i] + '">' + response[i] + '</option>';
          }

          $('#dependentOption').append(options);
        }
      }
    );
  }

  function ajaxCall(url, data) {
    return $.ajax({
      url: url + data,
      data: '',
      type: 'GET',
      contentType: 'application/json; charset=utf-8'
    });
  }
</script>

Controller:

[HttpGet]
public ActionResult Index()
{
  // populate the viewmodel
  return View(viewmodel);
} 

[HttpPost]
public ActionResult Index(MyViewModel model)
{
  // Use model binding to 
  // get user input.
  // Then save the changes.
  // Return some action
}

[HttpGet]
public JsonResult GetDependentOptions(string independentOption)
{
  var result = new List<string>();

  result.Add("Select"); // optional

  // logic to populate the dependent dropdown
  // based on the choice made in the independent
  // dropdown.

  return Json(result);
}