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.