我正在通過AJAX進行ASP.NET MVC調用方法,該錯誤會引發異常。我想把異常的消息傳回客戶端,我寧願不必去捕捉異常。事情是這樣的:ASP.NET MVC Ajax錯誤返回視圖,而不是Ajax
[HttpPost]
public ActionResult AddUser(User user) {
if (UserIsValid(user)) {
return Json(new { resultText = "Success!" });
}
throw new Exception("The user was invalid. Please fill out the entire form.");
}
我看到在我的螢火響應的HTML頁面
<!DOCTYPE html>
<html>
<head>
<title>"The user was invalid. Please fill out the entire form."</title>
.....
我想不會被迫使用try catch塊來做到這一點。有沒有一種方法可以自動獲取jQuery $(document).ajaxError(function(){}來讀取這個異常消息?這是不好的做法嗎?我可以重寫控制器OnException嗎?或者我必須嘗試/ catch並返回?JSON
像這樣的事情將是很好:
$(document).ajaxError(function (data) {
alert(data.title);
});
我想你可以使用說明(這裏)的方法(http://stackoverflow.com/questions/4707755/asp- net-mvc-ajax-error-handling)並修飾你的控制器動作方法,該方法返回帶有屬性過濾器的json。 –