2013-06-13 152 views
1

視圖的路徑我有這個類:動態更改

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

而且我想檢索和被另一個取代執行視圖的路徑。我試圖在web調用中調試查看過濾器上下文,但是我沒有設法找到即將呈現的視圖。

我該怎麼做?

回答

5

MSDN來自:

Controller.OnActionExecuting Method:調用調用動作方法之前。在此階段,由於Action尚未執行,因此不存在ActionResult

你最好使用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); 
} 
+0

視圖名稱是'「指數」'或'「」'從不完整視圖路徑。我如何獲得像「〜/ Views/Controller/ViewName」這樣的字符串? – AgentFire

+0

我相應地修改了我的答案。 – haim770

+0

viewResult.View'屬性始終爲空,即使視圖名最初是正確的。 – AgentFire