获取(int)asp.net wep api

时间:2017-03-30 03:42:24

标签: jquery ajax asp.net-web-api get

我现在真的很困惑我的网络API。这是我的Get方法代码:

public Employee Get(int id)
{
            using (EmployeeDBEntities entities = new EmployeeDBEntities())
            {
                return entities.Employees.FirstOrDefault(e => e.ID==id);
            }
        }   

我使用jquery ajax来实现:

$(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);
                });
            }
        });
    });
});

当我运行它时,它只返回了很多未定义的&#39;。但是,当我运行&#34; http://localhost:52178/api/employees/1&#34;在浏览器中,我得到了我想要的正确的xml。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

尝试将Ajax调用中的URL更新为&#34; / api / employees / 1&#34; - 具有前导斜杠

答案 1 :(得分:0)

在ajax选项中使用contentType: "application/json; charset=utf-8"

 $.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);
            });
        }
    });