drewwyatt
drewwyatt

Reputation: 6027

How do I return a response my ajax call understands as a success without using an API controller?

My application is making a call that is working, but the script making the call just doesn't know it because I don't know what type of response it is expecting.

An MVC API controller can return an HttpResponseMessage object, but I need to have access to some session objects when I make the API call, so I can't use an API controller.

Right now my controller is just returning:

return View();

But what should I return so that my ajax call:

$('#deleteReservations').click(function() {
        var clickedYes=confirm('Are you sure?');
        if (clickedYes) {
            console.log('boom');
            $.ajax({
            type: 'DELETE',
            url: '@Html.Action("DeleteCurrentReservations", "reservation"),
            data: { UserID: @TTU_RaiderGate.Helpers.SessionManager.CurrentUser.ID, GameID: @TTU_RaiderGate.Helpers.AppSettings.CurrentGameID },
            //dataType: "json",
            traditional: true,
            success: function (response) {
                $('#lot').html('<i class="fa fa-cog fa-spin fa-5x black"></i>');
                $('#lot').load('@Url.Action("AsTable", "Lot")', function(){
                });
            },
            error: function(response) {
                console.log('no');
            }
            });
            console.log('pow');
        } else {
            alert('false');
        }
});

Triggers the success function?

Upvotes: 1

Views: 953

Answers (2)

petelids
petelids

Reputation: 12815

I would use a JsonResult. The method will return an HTTP 200 so it will go into your success callback but you can also return JSON to handle errors with your deletion:

public JsonResult DeleteCurrentReservations
{
    if (Request.IsAjaxRequest())
    {
        bool success = true;

        //perform your task here and set success to the correct value

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

Then in your success handler

success: function (data) {
    if (data.success == true) {
         //the call succeeded and you returned true in your Json
    }
    else {
         //the call succeeded but you returned false in your Json
    }
}

Upvotes: 2

Tim
Tim

Reputation: 15237

There's JsonResult, which derives from ActionResult so it can be returned from any controller. That's likely your best bet.

As long as your status code is a success (which it is by default) then whatever you return in the JsonResult will trigger the success handler.

Upvotes: 1

Related Questions