K7Buoy K7Buoy - 28 days ago 6
Ajax Question

Trouble building a select list in razor view using ajax call to mvc controller returning JSON object

As the title says I am having a bit of trouble with this. I have succeeded hardcoding the JSON but once I begin to use a model it goes wrong. Please see what I have to-date below.

Ajax

$(document).ready(function () {
$.getJSON('/Programs/GetAll', function (data) {

//clear the current content of the select
$('#ProgramId').empty();

//iterate over the data and append a select option
$.each(data, function (key, val) {
$('#ProgramId').append('<option id="' + key + '">' + val + '></option>');})
});
});


Controller

[HttpGet]
public JsonResult GetAll()
{
var progams = _context.Program
.Select(a => new
{
id = a.Id.ToString(),
name = a.Name
}).ToList();

return Json(progams);
}


Current outcome
It is not handling the returned object

Current object
Object looks ok

This hardcoding works with the ajax, js and html.

[HttpGet]
public JsonResult Get()
{
Dictionary<string, string> programSelectList = new Dictionary<string, string>();
programSelectList.Add("1", "Bob");
programSelectList.Add("2", "Cratchett");
return Json(programSelectList);
//return Json(_context.Program.ToJson());
}


I am missing something basic, no doubt, and any help would be greatly appreciated.

Thanks.

Answer

The response coming back from your ajax call is an array of items each with an id and name property. So when you use $.each to loop through them, the variable val will be a single js object with those 2 properties. You just need to access those properties to set the option value and text.

$.each(data, function (key, val) {
    $('#ProgramId').append('<option value="' + val.id + '">' + val.name + '</option>');
});

Also, you probably need to specify JsonRequestBehavior when returning json data from a GET action method.

return Json(progams,JsonRequestBehavior.AllowGet);
Comments