I have two dropdowns. One is populated with vehicle makes
<select id="vehicleMake" name="VehicleMake">
@foreach (var item in Model.Cars)
{
if (@item.Category == 1072)
{
<option value="@item.UniqueId">@item.Description</option>
}
}
</select>
The other one is empty and should be populated with vehicle models
@Html.DropDownListFor(model => model.VehicleModel, Enumerable.Empty<SelectListItem>(), "Select your model", new {@id="vehicleModel" })
This is my controller:
[HttpPost]
public JsonResult GetVehicleModels(string vehicleMake)
{
var vehicleModels = db.Glossaries.Where(x => x.VehicleMakeId.Contains(vehicleMake)).Select(x => x.Description).Distinct().ToList();
SelectList list = new SelectList(vehicleModels);
return Json(new { Success = true, Result = list }, JsonRequestBehavior.AllowGet);
}
This is the AJAX call:
<script type="text/javascript">
$("#vehicleMake").on('change', function () {
alert($(this).val());
$.ajax({
type: "POST",
url: "/Registration/GetVehicleModels",
data: JSON.stringify({ 'vehicleMake': $(this).val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
result = $.parseJSON( results );
var toAppend = '';
$.each(result,function(i,o){
toAppend += '<option>' + o.Text + '</option>';
});
$('#vehicleModel').append(toAppend);
},
failure: function (response) {
alert("failure");
},
error: function (response) {
alert("error" + response.responseText);
}
});
});
</script>
This is the results I'm getting in Developer Tools in Chrome (when 'Chevrolet' is chosen)
Success: true
Result: [{Disabled: false, Group: null, Selected: false, Text: "BROUGHAM", Value: null},…]
0: {Disabled: false, Group: null, Selected: false, Text: "BROUGHAM", Value: null}
Disabled: false
Group: null
Selected: false
Text: "BROUGHAM"
Value: null
The dropdown is populated with 'undefined'. What am I doing wrong?
See Question&Answers more detail:os