What to return from ASP.NET MVC action to allow jQuery ajax success event to fire?
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).
2 quick notes for anyone landing here struggling to trigger the ajax jQuery success
callback from an MVC controller:
- If you're using
type: "GET"
in your Ajax, you'll need to includeJsonRequestBehavior.AllowGet
to bypass the default anti JSON Hijacking security measures
return Json(true, JsonRequestBehavior.AllowGet);
- As per above, if you've indicated
dataType: 'json'
in the Ajax request, if you are making a one-way call (e.g.Save
) where you don't need anything back, you can return just about anything serializable asJson
from the controller. But with a 200, something must be returned. Use a 204 if no data is returned.
Wrong - Triggers the Ajax error
handler !
// Nope - Status 200 must have some content
return new HttpStatusCodeResult(HttpStatusCode.OK);
// Also returns a 200 with no data - not allowed
return new EmptyResult();
Works - triggers the Ajax success handler:
// Return a 204 if there's no data
return new HttpStatusCodeResult(HttpStatusCode.NoContent);
// Return something with a 200 return
return Json(new {Success = true});