0
<script>
    $(document).ready(function () {

        $('#dropdown').change(function () {
            var val = $(this).val();
                $.post("@Url.Action("GetServices","vas")", { catId: $(this).val() }, function (data) {
                    $('#dropdownServices').val(data);// here how to fill dropdownlist with the returned selected item.
                });

        });
    });
</script>

The HTML

 @Html.DropDownListFor(x => x.SelectedItem, new SelectList(Model.ListOfServices, "Value", "Text"),"choose an Option");
NinjaNye
  • 7,046
  • 1
  • 32
  • 46
sawa we
  • 521
  • 1
  • 4
  • 7

1 Answers1

0

Assuming your controller action returns a JSON result containing Value and Text properties:

[HttpPost]
public ActionResult GetServices(int catId)
{
    // This is probably coming from a database or something but you should
    // respect the JSON structure. Make sure you project your collection
    // to a list of elements where each element contains Value and Text properties
    // because they will be used on the client to bind the dropdown

    return Json(new[]
    {
        new { Value = "1", Text = "item 1" },
        new { Value = "2", Text = "item 2" },
        new { Value = "3", Text = "item 3" },
    });
}

you could bind the dropdown like this:

var url = '@Url.Action("GetServices", "vas")';
$.post(url, { catId: $(this).val() }, function (data) {
    var ddl = $('#dropdownServices');
    ddl.empty();
    $.each(data, function() {
        ddl.append(
            $('<option/>', {
                value: this.Value,
                html: this.Text
            })
        );
    });
});

Also make sure that you have applied the proper id attribute to your dropdown so that the $('#dropdownServices') selector used here will actually return something:

@Html.DropDownListFor(
    x => x.SelectedItem, 
    new SelectList(Model.ListOfServices, "Value", "Text"),
    "choose an Option",
    new { id = "dropdownServices" }
);

By the way if you are building some cascading dropdown lists you may find the following answer useful.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928