我有一个将表单提交到 MVC 控制器的函数,如下所示 -
function submitForm() {
$.ajax
({
type: 'POST',
url: '/Users/Index',
data: $('#searchForm').serialize(),
beforeSend: function() {
$('.usersearchresult').fadeOut('fast', function () { $('.loadinggif').show(); });
},
success: function (response) {
$('.loadinggif').hide();
$('.usersearchresult').hide().html(response).fadeIn('normal');
},
error: function (response) {
alert(response);
$('.loadinggif').hide();
$('.usersearchresult').hide().html(response).fadeIn('normal');
}
});
return false;
}
我想要一个中心位置来捕获错误,所以我扩展了HandleErrorAttribute
-
public class ClientExceptionAttribute : HandleErrorAttribute
{
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public override void OnException(ExceptionContext context)
{
Log.Error(context.Exception);
context.ExceptionHandled = true;
// Verify if AJAX request
if (context.HttpContext.Request.IsAjaxRequest())
{
// Use partial view in case of AJAX request
var result = new PartialViewResult();
result.ViewName = "~/views/shared/error.ascx";
context.Result = result;
}
}
}
错误视图很简单——
@model String
@{
Layout = null;
}
<div class="exception">
<img src="../Content/Graphics/warning.png" />
<br />
<div class="message">@(String.IsNullOrEmpty(Model) ? "User Entry Api is currently unavailable" : Model) </div>
</div>
问题是 AJAX 错误永远不会呈现部分视图 (error.cshtml) - 它只是给了我一个空白屏幕。
所以我有两个问题——
- 如何让 AJAX 呈现部分错误视图
- 如何将模型传递给部分视图
ClientExceptionAttribute
谢谢!