[英]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.