0

I have two combo boxes: one for Clients, and one for Projects. The idea is that when the Client is selected, the Projects combo is then populated. In my MVC code, the combos simply look like:

@Html.DropDownListFor(Function(model) model.ClientID, New SelectList(Model.Clients, "ClientID", "Name"), New With {.id = "SelectedClientID"})
@Html.DropDownListFor(Function(model) model.ProjectID, Enumerable.Empty(Of SelectListItem), New With {.id = "SelectedProjectID"})

Where the Client combo has an ID of SelectedClientID and the Project combo has an ID of SelectedProjectID.

My problem is my javascript, which triggers an action in my controller when a Client is selected.

<script type="text/javascript">
    $(function () {
        $('#SelectedClientID').change(function () {
            var selectedClientID = $(this).val();
            $.getJSON('@Url.Action("GetProjects")', { ClientID: selectedClientID }, function (projects) {
                var projectsSelect = $('#SelectedProjectId');
                projectsSelect.empty();
                $.each(projects, function (index, project) {
                    projectsSelect.append(
                        $('<option/>')
                            .attr('value', project.ProjectID)
                            .text(project.Name)
                    );
                });
            });
        });
    });
</script>


Function GetProjects(ClientID As Integer) As ActionResult
    Return Json(db.ppProjects.Where(Function(c) c.ClientID = ClientID), JsonRequestBehavior.AllowGet)
End Function

This code is mostly taken from this example. When I debug, I select a Client from the Client combo. This triggers the .change function. The GetProjects Action is correctly called and returns its JSON. But then the javascript just stops. It never makes it to the code afterwards, it skips all of the success function, function(projects).

What could be causing this to happen?

I have also tried replacing my $.getJSON line with a synchronous call like so:

$.ajax({ datatype: "json", url: "GetProjects", data: { ClientID: selectedClientID}, async: false }).done(function (projects) {

but with the same results, success code gets skipped still.

Community
  • 1
  • 1
ElliotSchmelliot
  • 7,322
  • 4
  • 41
  • 64

1 Answers1

0

Your code looks correct. Try using done() instead of the success callback:

$.getJSON('@Url.Action("GetProjects")', { ClientID: selectedClientID })
        .done(function (projects) {
                var projectsSelect = $('#SelectedProjectId');
                projectsSelect.empty();
                $.each(projects, function (index, project) {
                    projectsSelect.append(
                        $('<option/>')
                            .attr('value', project.ProjectID)
                            .text(project.Name)
                    );
                });
            });
Andy T
  • 10,223
  • 5
  • 53
  • 95