0

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

That's the one! Thank you, I knew it was something simple I was missing. Really appreciate the quick response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.