如何在OnActionExecuting中返回部分视图?

时间:2015-02-08 21:36:33

标签: c# asp.net-mvc asp.net-mvc-3

如果某个会话变量为空,我有点困惑我想导致部分视图而不是redirectResult。可能吗?如果是这样的话?我可以看到有一个PartialViewResult,但我无法弄清楚如何使用它。

 public class XXActionFilter : ActionFilterAttribute, IActionFilter
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext context = HttpContext.Current;

            if ((context.Session[item] == null))
            {
                filterContext.Result = my partial view
                return;              
            }


            base.OnActionExecuting(filterContext);
        }
    }

1 个答案:

答案 0 :(得分:4)

您应该将PartialViewResult的实例传递给Result属性:

public class XXActionFilter : ActionFilterAttribute, IActionFilter
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext context = HttpContext.Current;

        if ((context.Session[item] == null))
        {
            var result = new PartialViewResult
            {
                 ViewName = "PathToView"
            };

            filterContext.Result = result;
            return;              
        }


        base.OnActionExecuting(filterContext);
    }
}