在更改第一个ddl时使用jquery ajax绑定下拉列表
我有两个下拉列表,第一个下拉列表的更改我想填充ajax中的第二个。 我在ajax中获取了SelectListItem如何将其传递给下拉列表来绑定它?
视图:
@Html.DropDownList("FirstID", ViewBag.Groups as IEnumerable ) @Html.DropDownList("SecondID", ViewBag.Policies as IEnumerable)
视图中的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 BuildSecondDropDownLists(int id) { Pol = new SelectList(GetData(), "SecondID", "Name"); ViewBag.Pol = Pol; return Pol; }
首先修复控制器操作,使其返回JSON而不是某些IEnumerable
。 请记住,在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( $('', { value: this.SecondID, html: this.Name }) ); }); }