Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

c# - 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. I get the SelectListItem in ajax how to pass that to drop down list to bind it?

view:

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

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

Ajax method in view:

$(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;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Start by fixing your controller action so that it returns JSON and not some IEnumerable<SelectListItem>. Remember that in ASP.NET MVC controller actions must return 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
            })
        );
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...