动态更改视图的路径

时间:2013-06-13 09:05:02

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

我有这堂课:

public abstract class MyController : Controller
{
  protected override void OnActionExecuting(ActionExecutingContext filterContext)
  {
      string viewPath = filterContext/*... .ViewPath*/;
      viewPath = "Some new View Path";
  }
}

我想用另一个检索并替换正在执行的视图的路径。我试图在Web调用上调试 - 查看过滤器上下文,但是我没有设法找到即将呈现的视图。

我该怎么做?

1 个答案:

答案 0 :(得分:5)

来自MSDN

Controller.OnActionExecuting Method:在之前调用调用操作方法。在此阶段,由于ActionResult尚未执行,因此不存在Action

您最好使用OnResultExecuting代替:

protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
    var viewResult = filterContext.Result as ViewResult;

    if (viewResult != null)
    {
        var razorEngine = viewResult.ViewEngineCollection.OfType<RazorViewEngine>().Single();
        var viewName = !String.IsNullOrEmpty(viewResult.ViewName) ? viewResult.ViewName : filterContext.RouteData.Values["action"].ToString();
        var razorView = razorEngine.FindView(filterContext.Controller.ControllerContext, viewName, viewResult.MasterName, false).View as RazorView;
        var currentPath = razorView.ViewPath;
        var newPath = currentPath.Replace("..", "...");
        viewResult.View = new RazorView(filterContext.Controller.ControllerContext, newPath, razorView.LayoutPath, razorView.RunViewStartPages, razorView.ViewStartFileExtensions);
    }

    base.OnResultExecuting(filterContext);
}