我有一个webapi应用程序,其中我有一个代码来填充视图中的表
控制器(Home)代码是
[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();
}
并在视野中
//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);
}
});
});
但是在执行之后,我得到了一个包含3列的表,并且所有列都有值&#39; undefined&#39; ,我已调试代码,并在onclick事件中,它将转到控制器,它返回正确的值,但到达视图时数据不正确(在ajax代码中)
答案 0 :(得分:1)
您可以将结果类型更改为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);
}