即时更改视图的路径 [英] Change the view's path on the fly

查看:87
本文介绍了即时更改视图的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上了这堂课:

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

我想检索执行视图的路径并将其替换为另一视图.我曾尝试在Web调用中调试查看过滤器上下文,但是我没有设法找到要渲染的视图.

And I'd like to retrieve and replace the executing view's path by another one. I have tried to debug-view the filter context on a web call, however I did not manage to find a view which is about to render.

我该怎么做?

推荐答案

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

Controller.OnActionExecuting Method: Called before the action method is invoked. At this stage, no ActionResult exists since the Action didn't execute yet.

您最好改用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);
}

这篇关于即时更改视图的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆