如果您想为特定控制器提供特殊的视图位置,在您希望 ProductController 视图转到 MyProduct 文件夹的情况下,您需要覆盖FindView
和FindPartialView
方法RazorViewEngine
:
public class MyRazorViewEngine : RazorViewEngine
{
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
if (controllerContext.Controller is ProductController)
{
string viewPath = "/Views/MyProduct/" + viewName + ".cshtml";
return base.FindView(controllerContext, viewPath, masterName, useCache);
}
return base.FindView(controllerContext, viewName, masterName, useCache);
}
public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
if (controllerContext.Controller is ProductController)
{
string partialViewPath = "/Views/MyProduct/Partials/" + partialViewName + ".cshtml";
return base.FindPartialView(controllerContext, partialViewPath, useCache);
}
return base.FindPartialView(controllerContext, partialViewName, useCache);
}
}
如果您可能想在每个控制器视图文件夹中添加“我的”,您的视图引擎应该如下所示
public class MyRazorViewEngine : RazorViewEngine
{
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
string viewPath = "/Views/My" + GetControllerName(controllerContext) + "/" + viewName + ".cshtml";
return base.FindView(controllerContext, viewPath, masterName, useCache);
}
public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
string partialViewPath = "/Views/My" + GetControllerName(controllerContext) + "/Partials/" + partialViewName + ".cshtml";
return base.FindPartialView(controllerContext, partialViewPath, useCache);
}
private string GetControllerName(ControllerContext controllerContext)
{
return controllerContext.RouteData.Values["controller"].ToString();
}
}
而不是在你的 Global.asax
protected void Application_Start()
{
//remove unused view engines, for performance reasons as well
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MyRazorViewEngine());
}