I am quite new to MVC and Jquery and I am trying to dynamically load data from a database to populate a dropdown list. Although the data is returned from the controller, it is not displayed in the dropdown. What is wrong here?
Here is my controller code:
public JsonResult GetReasonforLeave(int typecode)
{
List<LeaveReason> reason_list = itlbg1.LeaveReasons.Where(f => f.LeaveType_typeCode == typecode).ToList();
return Json(reason_list, JsonRequestBehavior.AllowGet);
}
Here's the jquery:
function getreason(selecteditem) {
sel_val = selecteditem.value;
$.getJSON("/Leave/GetReasonforLeave", { typecode: sel_val })
.done(function (data) {
var options = $("#reason");
$.each(data, function (item) {
options.append($("<option />").val(item.reasonID).text(item.description));
});
});
}
$.each(data, function (index, item) {LeaveReasoncontains only 2 properties (reasonIDanddescription) you are sending unnecessary data across the wire - consider sending just the 2 properties you need -var data = itlbg1.LeaveReasons.Where(f => f.LeaveType_typeCode == typecode).Select(r => new { value = r.reasonID, text = description });alert(data);did not return any data. What is meant here by the index variable?Integer indexInArrayandObject value