我在控制器中有几个类似的方法:
[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);
}
虽然这段代码能够工作,但我不喜欢这种方法,因为:
- try/catch语句很耗费资源
- 代码捕获了System.Exception异常
- 代码难看
现在我知道我可以使用OnException或HandleError属性。
我还研究了一下ELMAH,这看起来很有前途。
但我仍然希望通过AJAX返回JSON给我的用户,以指示操作是否成功。
所以我的问题是,有没有人使用过这三种方法之一(或者具体使用ELMAH)来通过AJAX返回JSON?