I have several methods in a controller that look like:
[HttpPost]
public ActionResult AddEditCommentToInvoice(string invoiceNumber, string comments)
{
var response = new { success = true, msg = "Comment saved", statusMsg = "Comment saved" };
try
{
var recordsModified = invoiceService.AddCommentsToInvoice(invoiceNumber, comments);
Log.Info(recordsModified ? "Updated Comment" : "Did not update Comment");
} catch (Exception ex) {
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new {
success = false,
msg = "There is missing field data",
statusMsg = ex.Message
}, JsonRequestBehavior.AllowGet);
}
return Json(response, JsonRequestBehavior.AllowGet);
}
While this code works, I'm not comfortable with this approach because:
- Try/Catches are expensive
- The code catches System.Exception
- The code is ugly
Now I know that I can use OnException or the HandleError attribute.
I also did some research on ELMAH and this looks promising.
But I still want to return JSON via AJAX to my user to indicate whether the operation was a success or not.
So my question is, has anyone used any of the three methods (or specifically ELMAH) to return JSON via AJAX?