Reputation: 19
I want to populate the drop down list using ajax but I'm getting an error. How to bind the Json result to the drop down list using ajax/jquery. So any help will be appreciated. This is my Controller.
public JsonResult GetMonths(int YearId)
{
CCIRepository _repository = CCIRepository.CreateRepository();
List<MonthListClass> list = new List<MonthListClass>();
list = _repository.GetMonthFromImportDate(YearId);
return Json(new SelectList(list, "Value", "Text"));
}
This is My Ajax code.
<p>
<h3>Year:</h3>@Html.DropDownList("Yearitems", (IEnumerable<SelectListItem>)ViewBag.SelectList, "Select Year")
<h3>Month:</h3>@Html.DropDownList("MonthItems",(IEnumerable<SelectListItem>)ViewBag.SelectMonthList,"Select Month")
</p>
<p><input type="submit" value="Search" /></p>
<script>
$(document).ready(function () {
$("#Yearitems").change(function () {
debugger;
alert($("#Yearitems>option:selected").attr("Value"));
$.ajax({
type: "Get",
url: '@Url.Action("GetMonths","AirtelManagement")',
data: { YearId: $("#Yearitems>option:selected").attr("Value") },
datatype: "Json",
success: function (data) {
debugger;
$("#MonthItems").empty();
$.each(data, function (index, item) {
debugger;
$("#MonthItems").append('<option>', {
value: item.value,
text: item.text
}, '</option>')
});
//$("#MonthItems").html(items);
},
error: function () {
alert("An Error Occured");
}
});
});
});
</script>
Upvotes: 0
Views: 2766
Reputation: 2670
Based on the information you provided I would make it like this
[HttpPost]
public JsonResult GetMonths(int YearId)
{
CCIRepository _repository = CCIRepository.CreateRepository();
List<MonthListClass> list = new List<MonthListClass>();
list = _repository.GetMonthFromImportDate(YearId);
return Json(list);
}
and in the script
type: "POST",
url: '@Url.Action("GetMonths","AirtelManagement")',
data: JSON.stringify({ YearId: $("#Yearitems").val() }),
datatype: "Json",
success: function (data) {
$("#MonthItems").html("");
$.each(data, function (index, item) {
debugger;
$("#MonthItems").append(new Option(item.MonthName, item.MonthSelectedId));
});
//$("#MonthItems").html(items);
},
Try it
Upvotes: 1