假设您的控制器操作返回一个 JSON 结果,其中包含Value和Text属性:
[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" },
});
}
你可以像这样绑定下拉列表:
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
})
);
});
});
还要确保您已将正确的 id 属性应用于下拉列表,以便$('#dropdownServices')此处使用的选择器实际上会返回一些内容:
@Html.DropDownListFor(
x => x.SelectedItem,
new SelectList(Model.ListOfServices, "Value", "Text"),
"choose an Option",
new { id = "dropdownServices" }
);
顺便说一句,如果您正在构建一些级联下拉列表,您可能会发现它following answer很有用。