mshwf
mshwf

Reputation: 7449

Calling GET method that return IHttpActionResult from AJAX?

AJAX works fine with the GetAll method that returns IQueryable, but with GetOne, it doesn't work and return "undefined" to the browser, here is the Get method in the ApiController class:

[ResponseType(typeof(Author))]
public IHttpActionResult GetAuthor(int id)
{
    Author author = db.Authors.Find(id);
    if (author == null)
    {
        return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound, $"Author with {id} not found."));
    }

    return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, author));
}

this is the AJAX function:

$.ajax({
    type: 'GET',
    url: 'api/Authors',
    dataType: 'json',
    data:{id:'1'},
    success: function (data) {
        list.empty();
        $.each(data, function (index, val) {
            var qualifier = val.AuthorId + ' - ' + val.Name;
            list.append('<li>'+qualifier+'</li>')
        });
    }
});

Is this because GetAuthor returns IHttpActionResult?

GetAuthors:

public IQueryable<Author> GetAuthors()
{
    return db.Authors;
}

Screenshot of the Console window:

enter image description here

Upvotes: 2

Views: 2711

Answers (2)

Nkosi
Nkosi

Reputation: 247123

Is this because GetAuthor returns IHttpActionResult

NO! The issue is how you are dealing with the response returned from the request.

The example action is returning a single author yet being treated like a collection on the client.

function GetData(id) {
    var url = 'api/Authors';
    if(id) url = url + '?id=' + id;
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        success: function (data) {
            list.empty();
            if (!jQuery.isArray(data)) data = [data]; // If a single object is returned, wrap it in an array
            $.each(data, function (index, val) {
                var qualifier = val.AuthorId + ' - ' + val.Name;
                list.append('<li>'+qualifier+'</li>')
            });
        }
    });
}

Upvotes: 3

maxime_039
maxime_039

Reputation: 494

As discussed over chat, we confirmed that the answer was a success.

However the data value was not an array and was returning something equivalent to:

{
    AuthorId: 1,
    Book: null,
    Name: "Name here"
}

Therefore the following jQuery code for the success will be valid:

success: function(data){ 
    var qualifier = data.AuthorId + ' - ' + data.Name; 
    list.append('<li>'+qualifier+'</li>'); 
}

Upvotes: 1

Related Questions