Sean Anderson
Sean Anderson

Reputation: 29311

How to indicate success with Web API 2?

I'm issuing a PATCH request to my server in order to update a title:

$.ajax({
    url: Settings.get('serverURL') + 'Playlist/UpdateTitle',
    type: 'PATCH',
    dataType: 'json',
    data: {
        id: model.get('id'),
        title: title
    },
    success: function () {
        console.log("Success!");
    },
    error: function (error) {
        console.error("Failure!");
    }
});

[Route("UpdateTitle")]
[HttpPatch]
public IHttpActionResult UpdateTitle(PlaylistDto playlistDto)
{
    using (ITransaction transaction = Session.BeginTransaction())
    {
        PlaylistManager.UpdateTitle(playlistDto.Id, playlistDto.Title);

        transaction.Commit();
    }

    return Ok();
}

Everything works great except for the fact that the ajax request's error callback is executed and not the success callback.

Before Web API 2, I was using the following method which did not have the problem. Clearly the issue is that I am returning an Ok result instead of a JSON success object:

[HttpPost]
public JsonResult UpdateTitle(Guid playlistId, string title)
{
    using (ITransaction transaction = Session.BeginTransaction())
    {
        PlaylistManager.UpdateTitle(playlistId, title);

        transaction.Commit();
    }

    return Json(new
        {
            success = true
        });
}

What's the proper way to indicate success with web API 2?

Upvotes: 1

Views: 6237

Answers (2)

Neil Smith
Neil Smith

Reputation: 2565

Return an HttpResponseMessage and set the StatusCode to OK:

public HttpResponseMessage UpdateTitle() {
    ...
    return Request.CreateResponse(HttpStatusCode.OK);
}    

Upvotes: 4

Sean Anderson
Sean Anderson

Reputation: 29311

The problem is actually pretty simple:

dataType: 'json',

tells jQuery to not use intelligent guessing for the server's response type. It will throw an error if the server does not respond with json. If I just delete that property then everything works as expected.

Upvotes: 5

Related Questions