skip to Main Content

I’m trying to make cascading dropdowns. The first one works fine but the second is not getting the data from the controller. The DeptID passes through to my GetStores parameter fine, but does not populate the second dropdown.

public ActionResult HistoryView()
{
  var model = new TemplateViewModel();
  model.Depts = _uow.Repository<Dept>().GetAll();

  ViewBag.listCompanies = new SelectList(_uow.Repository<Dept>().GetAll(),"DeptID","Dept_Name");

  return View(model);
}

public JsonResult GetStores( int DeptID)
{
  TemplateViewModel templateViewModel = new TemplateViewModel
  {
    Dept = _uow.Repository<Dept>().Get(x => x.DeptID == DeptID),
    Templates = _uow.Repository<Template>().GetAll().ToList()
  };
  return Json(templateViewModel, JsonRequestBehavior.AllowGet);
}
<div style="background-color:azure; border-color:black; border:solid">
  <br />
  <div>
    <b>Select your Company:</b>
  </div>
  <div>
    @Html.DropDownList("DeptID", (IEnumerable<SelectListItem>)ViewBag.listCompanies,String.Empty,  new {style = "width: 200px;"})
  </div>
  <br />
  <div>
    <b>Select Store</b>
    <div>
      @Html.DropDownList("TemplateID", new SelectList(string.Empty, "Value", "Text"), "--Select Store--", new { style = "width:200px;" } )
    </div>
  </div>
</div>
<script>
  $(document).ready(function() {
    $("#DeptID").change(function() {
      $("TemplateID").empty();
      $.getJSON('/HistoryLog/getstores', { DeptID: $('#DeptID').val() }, function(data) {
        $.each(data, function () {
          $('#TemplateID').append('<option value=' + this.Value + '>' + this.Text + '</option>');
        });
      });
    });
  });
</script>

enter image description here

enter image description here

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    enter image description here

    Thanks for all the help above, i also needed to create a Helper to searialize the data so i add it and it works!


  2. $("TemplateID").empty();
    

    this line is incorrect because you are not selecting any Tag, you are selecting an element of a dropdown.

    so corrected version will be the:

    $("#TemplateID").empty();
    

    Then, you are looping on data. Here data is a object and it has property name Templates which you want to populate. So the corrected version will be the:

    $.each(data.Templates, function () {
    

    and last one is add quotes around the value in the append method. It will prevent potential issues with special characters in the values:

    $('#TemplateID').append('<option value="' + this.Value + '">' + this.Text + '</option>');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search