I really confused with my web api now. Here is my code for Get method:
public Employee Get(int id)
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
return entities.Employees.FirstOrDefault(e => e.ID==id);
}
}
And I use jquery ajax to get that:
$(document).ready(function () {
$('#btn').click(function () {
$.ajax({
url: 'api/employees/1',
method: 'GET',
success: function (data) {
$('#ul').empty();
$.each(data, function (index, value) {
var row = $('<tr><td>' + value.ID + '</td><td>'
+ value.FirstName + '</td><td>'
+ value.LastName + '</td><td>'
+ value.Gender + '</td><td>'
+ value.Salary + '</td></tr>');
$('#ul').append(row);
});
}
});
});
});
when I ran it, it just returned lots of 'undefined'. However when I run "http://localhost:52178/api/employees/1" in browser, I got the right xml I want. Can anyone help me with that?
Try updating the URL in your Ajax call to "/api/employees/1" - which has the leading slash
Use contentType: "application/json; charset=utf-8"
in ajax options
$.ajax({
url: 'api/employees/1',
method: 'GET',
contentType: "application/json; charset=utf-8",/*use this option*/
success: function (data) {
$('#ul').empty();
$.each(data, function (index, value) {
var row = $('<tr><td>' + value.ID + '</td><td>'
+ value.FirstName + '</td><td>'
+ value.LastName + '</td><td>'
+ value.Gender + '</td><td>'
+ value.Salary + '</td></tr>');
$('#ul').append(row);
});
}
});