How can I load data from controller (JSON) to a ListBox in View?

Viewed 47

I am new in ASP.NET Core. I just want to simply load a JSON file's data into a listbox.

Here is the controller class:

 public class EmployeeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
    [HttpGet]
    public JsonResult GetEmpList()
    {
        var empList = new List<Employee>()
        {
            new Employee { Id=1, Name="Manas"},
            new Employee { Id=2, Name="Tester"}
        };

        return Json(empList);
    }

}

And here is the view:

<select id="ddlEmployees"></select>
<script>
var ddlEmployees = $("#ddlEmployees");
$.ajax({
    type: "GET",
    url: "/EmployeeController/GetEmpList",
    dataType: 'JSON',
    contentType: "application/json",
    success: function (data) {
        alert(data);
        for (var i = 0; i < data.length; i++) {
            ddlEmployees.append('<option> ' + data[i] + '</option >');
        }
    }
}); </script>
2 Answers

Assuming that you are successfully able to make requests to your API endpoint I think the part that needs to be updated is actually your jQuery in the view. Since you're returning a list as JSON, what you'll have in your data argument is an array of objects. So in order to populate the values of the <option> tag with the values in your JSON object, you'll need to access the JSON fields that you define in your Controller.

<select id="ddlEmployees"></select>
<script>
var ddlEmployees = $("#ddlEmployees");
$.ajax({
    type: "GET",
    url: "/EmployeeController/GetEmpList",
    dataType: 'JSON',
    contentType: "application/json",
    success: function (data) {
        alert(data);
        for (var i = 0; i < data.length; i++) {
            ddlEmployees.append('<option value="' + data[i].Id + '"> ' + data[i].Name + '</option >');
        }
    }
}); </script>

The naming convention for response json in asp.net core is camel case instead of pascal case.

You could add console.log(data) to check the response in Console panel(press F12 in browser). Then you will find the property name in response is camel case.

Change like below:

$.ajax({
    type: "GET",
    url: "/Employee/GetEmpList",   //it should be Employee/xxx instead of EmployeeController/xxx
    dataType: 'JSON',
    contentType: "application/json",
    success: function (data) {
        console.log(data);
        for (var i = 0; i < data.length; i++){
            ddlEmployees.append('<option value="' + data[i].id + '"> ' + data[i].name + '</option >');
        }
    }
});
Related