PartialViewResult返回带有母版页的视图

时间:2012-01-26 08:55:20

标签: asp.net-mvc

我编写了自己的HandleError属性。

当ajax请求期间发生错误时,我想返回一个部分视图,当请求不是ajax时,应该返回一个包含母版页的视图。

到目前为止我写了这个

     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class IcpHandleErrorAttribute : FilterAttribute, IExceptionFilter
{
    private readonly Type _exceptionType = typeof(Exception);

    public IcpHandleErrorAttribute()
    {} 

    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)throw new ArgumentNullException("filterContext");

        if (filterContext.IsChildAction)return;

        if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)return;

        Exception exception = filterContext.Exception;

        if (new HttpException(null, exception).GetHttpCode() != 500)return;

        if (!_exceptionType.IsInstanceOfType(exception))return;

        var controllerName = (string)filterContext.RouteData.Values["controller"];
        var actionName = (string)filterContext.RouteData.Values["action"];

        var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

        ViewResultBase result;

        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            result = new PartialViewResult { ViewName = "ErrorAjax" };
        }
        else
        {
            result = new ViewResult{ViewName = "Error"}; 
        }

        result.ViewData = new ViewDataDictionary<HandleErrorInfo>(model);
        result.TempData = filterContext.Controller.TempData;

        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = 500;

        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}

但即使将PartialViewResult分配给结果,也会返回母版页。 为什么会这样?

ErrorAjax局部视图

@model HandleErrorInfo

@{
    Layout = null;
}

<div class="error">@Model.Exception.Message</div>

通过jquery的帖子调用该动作。

动作方法是一个测试用例

[HttpPost]
public ActionResult Create(ProjectCreateCommand command)
{
    throw new NotImplementedException("ajax");

    return Post(command);
}

global.asax的Application_Start()方法中的attribte注册。

    GlobalFilters.Filters.Add(new IcpHandleErrorAttribute());

    RegisterGlobalFilters(GlobalFilters.Filters);

2 个答案:

答案 0 :(得分:1)

您似乎没有对result局部变量执行任何有用的操作,例如将其分配给过滤器上下文:

filterContext.Result = result;

答案 1 :(得分:0)

如果这不是Ajax请求,则需要重定向到某个Action。并在此操作中返回View()