Cascading dropdowns MVC 3

2019-06-23 17:55发布

问题:

I am about to create cascading dropdown lists in MVC 3. Logik is simple, for each location there may be many Employees, so best way i could figure out how to implement it is drop downlists.

what i have right now is :

1 list is filled up at begninnging with Locations. and on change i can get data into second my Employee list, but the data i transfer is Enumrable dates".

As soon as i try to send Employees over with ID and name nothing happend.

Controller code:

public ActionResult Months(string locId)
{
  var k = service.getEmployeeForLocation(Int32.Parse(locId))
                 .ToList()
                 .Select(x => new
                         {
                           Value = .EmployeeId,
                           Text = x.Name 
                         });

  return Json(k,JsonRequestBehavior.AllowGet); 
}

View :

<tr>
<td>Choose your closest location : 
    @Html.DropDownListFor(x => x.SelectedLocation, Model.Locations)</td>
<td>Choose your closest location : 
    @Html.DropDownListFor(x => x.SelectedEmployee, 
                          Enumerable.Empty<SelectListItem>(), "-- select month --")
</tr>

Javascript

</script>
<script type="text/javascript">
    $('#SelectedLocation').change(function () {
        var selectedLocation = $(this).val();
        if (selectedLocation != null && selectedLocation != '') {
            $.getJSON('@Url.Action("Months")', { locId: selectedLocation }, 
            function (employee) {

                var EmployeeSelect = $('#SelectedEmployee');
                //                monthsSelect.empty();

                $.each(employee, function (index, employee) {
                    EmployeeSelect.append($('<option/>', {
                        value: employee.value,
                        text: employee.text
                    }));
                });
            });

        }
    });
</script>

回答1:

One thing that I can see is that your variable names in your action start with an upper case and JavaScript is case sensitive. In your page you are using lowercase but they two should be upper case if you want to keep the casing in your controller.