Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
like image 818
Altaf Sami Avatar asked Jun 03 '13 12:06

Altaf Sami


People also ask

How to bind data to DropDownList in MVC using AJAX?

First add your select tag to create dropdownlist in html. Now add your jQuery reference on the top as we know that to use jQuery we need to add the library on the top. Now create Index action which initiate the index page and another action named ShowData which returns the records in JSON format.

How can we create dynamic drop down list in HTML using jQuery?

To add a dropdown list dynamically, you would need to create the HTML <select> element, its label and optionally a <br> tag. In pure JavaScript, you can use the document. createElement() method to programmatically create a dropdown list. Then you can call the Node's appendChild() method or jQuery's .


1 Answers

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
            })
        );
    });
}
like image 142
Darin Dimitrov Avatar answered Oct 20 '22 17:10

Darin Dimitrov