Miranda Johnson Miranda Johnson - 13 days ago 5
jQuery Question

MVC Cascading Dropdown using JQuery AJAX

I have a drop down list of US states. When the user selects the state another drop down list of county/parrish is to be populated. I am pulling the information to populate the county drop down from a stored procedure. The problem I have is that it is returning object Object for each county and I do not know what to do to correct this.

here is the code in the controller

public ActionResult FillCountyList(string State)
{
Models.CountyList mod = new CountyList();
mod.TheState = State;
List<ListCountiesByState_Result> Counties = mod.ListCounties();
return Json(Counties, JsonRequestBehavior.AllowGet);
}


I have also tried to the following in my controller and it also returns a list showing object Object for each county

public JsonResult FillCountyList(string State)
{
IEnumerable<SelectListItem> Counties = db.ListCountiesByState(State).Select(c => new SelectListItem {
Value = c.County,
Text = c.County
}).ToList();
return Json(Counties, JsonRequestBehavior.AllowGet);
}


Here is the jquery code in the view

$('#State').change(function () {
var stateid = $('#State').val();
$.ajax({
url: '/Profile/BackgroundData/FillCountyList',
type: 'GET',
datatype: 'JSON',
data: { State: stateid },
success: function (result) {
$('#CountyOrParrish').html('');
$('#CountyOrParrish').append($('<option>Make Selection</option>'));
$.each(result, function (i, item) {
$('#CountyOrParrish').append($('<option></option>').text(item));
});
}
});
});

Answer

Check That your method returns countries correctly. Also change:

$('<option></option>').text(item));

to:

$('<option></option>').val(item.Value).html(item.Text));
Comments