What to return from ASP.NET MVC action to allow jQuery ajax success event to fire?

Viewed 26958

Right now my ajax posts all fire their Error events even if the action did not cause an error. I have an ASP.NET MVC action that looks like:

[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult StuffToDo(int id)
{
     // do various things that work ...
     return new JsonResult(); // i have to return something, so this...
}

On the client side I have this jQuery:

$('#actionClick').click(function() {
     if (confirm('Are you sure?')) {
         $.ajax({
             type: "POST",
             url: "/Customer/StuffToDo/<%= Model.Customer.Id %>",
             contentType: "application/json; charset=utf-8",
             data: "{}",
             dataType: "json",
             success: function() {
                 ShowSuccessResult("Yay!");
             },
             error: function(xhr, ajaxOptions, thrownError) {
                 ShowErrorResult("Boo! Message:" + xhr.responseText);
             }
         });
      }
      return false;
 });

If the action is successful (no exceptions thrown) then I would expect the success event handler to be triggered. Instead the error event is firing. Is there something I should pass back or change in the action so the success event fires?

I realize this question is basically the same as this other question, but my error handler already has the expanded signature which solved the other person's question.

I changed the return value to Null to see if that affected anything, but no behavior change.

Its starting to look like this is an issue with HTTPS. I get multiple responses from the request. The first 2 are 401 messages and then I get a 200.

4 Answers

I believe the problem is that you're not returning anything in the JsonResult. Try:

return this.Json(string.Empty);

and see if that works. I think that the problem is that you're returning nothing to the jQuery call rather than an empty JSON set:

{}

Returning an empty result may also be useful

return new EmptyResult();

Note: Your return type doesn't need to be ActionResult or event anything that inherits from it. In fact mvc will let you call any public method. However you should always use the most explicit return type you want just like any other method (like JsonResult).

Related