[英]bind drop down list using jquery ajax on change of first ddl
我有两个下拉列表,第一个下拉列表的更改我想填充ajax中的第二个。 我在ajax中获取了SelectListItem如何将其传递给下拉列表来绑定它?
视图:
@Html.DropDownList("FirstID", ViewBag.Groups as IEnumerable<SelectListItem> )
@Html.DropDownList("SecondID", ViewBag.Policies as IEnumerable<SelectListItem>)
视图中的Ajax方法:
$(function () {
$('#FirstID').change(function () {
var selectedValue = $(this).val();
$.ajax({
url: '@Url.Action("BuildSecondDropDownLists", "controller")',
type: "POST",
data: { id: selectedValue },
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
},
success: function (result) {
alert(result);
//here how i can bind second drop down list
}
});
});
});
控制器:
public IEnumerable<SelectListItem> BuildSecondDropDownLists(int id)
{
Pol = new SelectList(GetData(), "SecondID", "Name");
ViewBag.Pol = Pol;
return Pol;
}
首先修复控制器操作,使其返回JSON而不是某些IEnumerable<SelectListItem>
。 请记住,在ASP.NET MVC控制器中,操作必须返回ActionResults:
public ActionResult BuildSecondDropDownLists(int id)
{
var result = GetData();
return Json(result, JsonRequestBehavior.AllowGet);
}
然后遍历返回的元素并将它们附加到第二个下拉列表:
success: function (result) {
var secondDdl = $('#SecondID');
secondDdl.empty();
$.each(result, function() {
secondDdl.append(
$('<option/>', {
value: this.SecondID,
html: this.Name
})
);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.