我知道您已经接受了答案,但这是我在Phil Haack 的帖子的帮助下尝试相同想法时得出的结论。
首先,您需要拥有自己的 ViewEngine 来查找 View 文件夹下的文件夹。像这样:(你会注意到它看起来很像 Phil Haack 的区号)
public class TestViewEngine : WebFormViewEngine
{
public TestViewEngine()
: base()
{
MasterLocationFormats = new[] {
"~/Views/{1}/{0}.master",
"~/Views/Shared/{0}.master"
};
ViewLocationFormats = new[] {
"~/{0}.aspx",
"~/{0}.ascx",
"~/Views/{1}/{0}.aspx",
"~/Views/{1}/{0}.ascx",
"~/Views/Shared/{0}.aspx",
"~/Views/Shared/{0}.ascx"
};
PartialViewLocationFormats = ViewLocationFormats;
}
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
ViewEngineResult rootResult = null;
//if the route data has a root value defined when mapping routes in global.asax
if (controllerContext.RouteData.Values.ContainsKey("root")) {
//then try to find the view in the folder name defined in that route
string rootViewName = FormatViewName(controllerContext, viewName);
rootResult = base.FindView(controllerContext, rootViewName, masterName, useCache);
if (rootResult != null && rootResult.View != null) {
return rootResult;
}
//same if it's a shared view
string sharedRootViewName = FormatSharedViewName(controllerContext, viewName);
rootResult = base.FindView(controllerContext, sharedRootViewName, masterName, useCache);
if (rootResult != null && rootResult.View != null) {
return rootResult;
}
}
//if not let the base handle it
return base.FindView(controllerContext, viewName, masterName, useCache);
}
private static string FormatViewName(ControllerContext controllerContext, string viewName) {
string controllerName = controllerContext.RouteData.GetRequiredString("controller");
string root = controllerContext.RouteData.Values["root"].ToString();
return "Views/" + root + "/" + controllerName + "/" + viewName;
}
private static string FormatSharedViewName(ControllerContext controllerContext, string viewName) {
string root = controllerContext.RouteData.Values["root"].ToString();
return "Views/" + root + "/Shared/" + viewName;
}
}
然后在您Global.asax
用您的自定义 ViewEngine 替换默认 ViewEngine 时,在Application_Start
:
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new TestViewEngine());
现在,当您在中定义路由时Global.asax
,您需要设置一个root
值,指示要在 View 文件夹下查找的文件夹,如下所示:
routes.MapRoute(
"ListManager",
"ListManager/{action}/{id}",
new { controller = "ListManager", action = "Index", id = "", root = "Manage" }
);