i have one webapi app in which i have one code to populate a table in the view
the controller(Home) code is
[HttpGet]
public List<Employee> GetEmployees()
{
var com = new TrainingDBEntities();
var records = from emp in com.tblEmployees
select new Employee
{
empID = emp.empID,
empName = emp.empName,
skill=emp.skill,
};
return records.ToList();
}
and in view
//show emp details
$('#btshw').click(function () {
$.ajax({
url: "/Home/GetEmployees",
success: function (result) {
console.log(result);
for (var i = 0; i < result.length; i++) {
var Row = "<tr><td>";
Row += result[i].empID + "</td><td>";
Row += result[i].empName + "</td><td>";
Row += result[i].skill + "</td><td>";
$('#emplist').append(Row);
}
$('#emplist').append("</table>");
}
,
error: function (err) {
alert(err.status.Text);
}
});
});
but after execution i got a table having 3 columns and all having values 'undefined' , i have debug the code and in the onclick event its going to the controller and it returns the correct value but data is not correct when reaching in the view(in ajax code)
You can change the result type to JsonResult:
[HttpGet]
public JsonResult GetEmployees()
{
var com = new TrainingDBEntities();
var records = from emp in com.tblEmployees
select new Employee
{
empID = emp.empID,
empName = emp.empName,
skill = emp.skill,
};
return Json(records.ToList(), JsonRequestBehavior.AllowGet);
}