-1

(sorry but I've searched related questions but ive only found this without answer: Drop-down list not populating other controls)

okay so I'am stuck here, first of all, I'am strickly backend .net developer but Im in situation where I need to help, okay so the problem is: i dont know how to populate second combo box which depends on the first one, for example, there are clients and contacts, every client has own contacts, so depending on which client you select, we need to show his contacts: how to do this? on the wpf platform, we simply have a on item selection changed event, something like that, and on changed we update the second combo box, but i have no idea how to do this in asp.net mvc, i pouplate the first combo box like this:

<div class="form-group">
            @Html.LabelFor(model => model.ClientID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ClientID", TempClass.GetClients, "Select Client")
            </div>
        </div>

Where TempClass.GetClients returns

IEnumerable<SelectListItem>

with values of: ID and the name of the client.

Hope you understand, Thanks in advance.

ShadyOverflow
  • 85
  • 3
  • 11
  • 2
    Possible duplicate of [Cascading drop-downs in MVC 3 Razor view](https://stackoverflow.com/questions/4458970/cascading-drop-downs-in-mvc-3-razor-view) and [Fill drop down list on selection of another drop down list](https://stackoverflow.com/questions/17013644) and [bind drop down list using jquery ajax on change of first ddl](https://stackoverflow.com/questions/16897146) and [Populate DropDownList from another DropDownList](https://stackoverflow.com/questions/44282775) – adiga Dec 11 '18 at 15:18

1 Answers1

2

Basically, you need to do the following step:

Using Jquery to catch the event of change in dropdown list http://api.jquery.com/change/

$("#Dropdown1").on("change", function(){
    var selectedValue = $(this).val();
    AjaxCall(selected);
})

Then, use Ajax to make a call to an action on controller which populate values for the second dropdown.

function AjaxCall(value){
    $.ajax({
        type: "GET",
        url : 'UrlToAction',
        data: { value: value },
        success: function(data) {
            PopulateValueForSecondDropdown(data);
        }
    });
}

Once you receive data from Ajax, in the success method, use jquery to populate values for the second dropdown

function PopulateValueForSecondDropdown(data) {
    $('#DROPDOWN2').empty(); 
    data.forEach(function(item){
        $('#DROPDOWN2').append('<option value="' + item.KEY+ '">' + item.VALUE + '</option>');
    });
}