5
在我的ASP.NET MVC 2應用程序中,我使用HandleErrorAttribute在未處理的異常情況下顯示自定義錯誤頁面,並且除非異常發生在由Ajax.ActionLink調用的操作中,否則它完美地工作。在這種情況下,沒有任何反應是否有可能使用HandleErrorAttribute來更新目標元素與「Error.ascx」部分視圖的內容?如何使HandleErrorAttribute與Ajax協同工作?
在我的ASP.NET MVC 2應用程序中,我使用HandleErrorAttribute在未處理的異常情況下顯示自定義錯誤頁面,並且除非異常發生在由Ajax.ActionLink調用的操作中,否則它完美地工作。在這種情況下,沒有任何反應是否有可能使用HandleErrorAttribute來更新目標元素與「Error.ascx」部分視圖的內容?如何使HandleErrorAttribute與Ajax協同工作?
要做到這一點,你可以寫一個自定義的行爲過濾:
public class AjaxAwareHandleErrorAttribute : HandleErrorAttribute
{
public string PartialViewName { get; set; }
public override void OnException(ExceptionContext filterContext)
{
// Execute the normal exception handling routine
base.OnException(filterContext);
// Verify if AJAX request
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// Use partial view in case of AJAX request
var result = new PartialViewResult();
result.ViewName = PartialViewName;
filterContext.Result = result;
}
}
}
,然後指定要使用的局部視圖:
[AjaxAwareHandleError(PartialViewName = "~/views/shared/error.ascx")]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult SomeAction()
{
throw new Exception("shouldn't have called me");
}
}
在你看來
最後假設你有以下鏈接:
<%= Ajax.ActionLink("some text", "someAction", new AjaxOptions {
UpdateTargetId = "result", OnFailure = "handleFailure" }) %>
您可以使handleFailure
函數更新適當的div:
<script type="text/javascript">
function handleFailure(xhr) {
// get the error text returned by the partial
var error = xhr.get_response().get_responseData();
// place the error text somewhere in the DOM
document.getElementById('error').innerHTML = error;
}
</script>
此頁面也值得閱讀,因爲它增加了更多信息到這個問題:http://jimmylarkin.net/post/2011/09/30/MVC-3-HandleError-Attribute-and- AJAX-Forms.aspx – 2014-04-17 23:38:19