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;
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
})
);
});
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0