动态更改视图的路径
本文关键字:路径 视图 动态 | 更新日期: 2023-09-27 18:18:24
我有这样一个类:
public abstract class MyController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
string viewPath = filterContext/*... .ViewPath*/;
viewPath = "Some new View Path";
}
}
我想检索并替换执行视图的路径为另一个。我曾尝试在web调用上调试查看过滤器上下文,但是我没有设法找到即将渲染的视图。
我该怎么做?
From 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);
}