Alt*_*ami 5 c# asp.net jquery razor asp.net-mvc-4
我有两个下拉列表,第一个下拉列表的更改我想填充ajax中的第二个.我在ajax中获取了SelectListItem如何将其传递给下拉列表来绑定它?
视图:
@Html.DropDownList("FirstID", ViewBag.Groups as IEnumerable<SelectListItem> )
@Html.DropDownList("SecondID", ViewBag.Policies as IEnumerable<SelectListItem>)
Run Code Online (Sandbox Code Playgroud)
视图中的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
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
控制器:
public IEnumerable<SelectListItem> BuildSecondDropDownLists(int id)
{
Pol = new SelectList(GetData(), "SecondID", "Name");
ViewBag.Pol = Pol;
return Pol;
}
Run Code Online (Sandbox Code Playgroud)
首先修复控制器操作,使其返回JSON而不是一些IEnumerable<SelectListItem>.请记住,在ASP.NET MVC控制器中,操作必须返回ActionResults:
public ActionResult BuildSecondDropDownLists(int id)
{
var result = GetData();
return Json(result, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
然后遍历返回的元素并将它们附加到第二个下拉列表:
success: function (result) {
var secondDdl = $('#SecondID');
secondDdl.empty();
$.each(result, function() {
secondDdl.append(
$('<option/>', {
value: this.SecondID,
html: this.Name
})
);
});
}
Run Code Online (Sandbox Code Playgroud)