简体   繁体   English

在更改第一个ddl时使用jquery ajax绑定下拉列表

[英]bind drop down list using jquery ajax on change of first ddl

I have two drop down lists, onchange of first drop downlist i want to populate the second one in ajax. 我有两个下拉列表,第一个下拉列表的更改我想填充ajax中的第二个。 I get the SelectListItem in ajax how to pass that to drop down list to bind it? 我在ajax中获取了SelectListItem如何将其传递给下拉列表来绑定它?

view: 视图:

                @Html.DropDownList("FirstID", ViewBag.Groups as IEnumerable<SelectListItem> )

                @Html.DropDownList("SecondID", ViewBag.Policies as IEnumerable<SelectListItem>)

Ajax method in view: 视图中的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

            }
        });
    });
});

Controller: 控制器:

  public IEnumerable<SelectListItem> BuildSecondDropDownLists(int id)
    {

        Pol = new SelectList(GetData(), "SecondID", "Name");


        ViewBag.Pol = Pol;

        return Pol;
    }

Start by fixing your controller action so that it returns JSON and not some IEnumerable<SelectListItem> . 首先修复控制器操作,使其返回JSON而不是某些IEnumerable<SelectListItem> Remember that in ASP.NET MVC controller actions must return ActionResults: 请记住,在ASP.NET MVC控制器中,操作必须返回ActionResults:

public ActionResult BuildSecondDropDownLists(int id)
{
    var result = GetData();
    return Json(result, JsonRequestBehavior.AllowGet);
}

and then loop through the returned elements and append them to the second dropdown: 然后遍历返回的元素并将它们附加到第二个下拉列表:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM