我知道你已經接受一個答案,但這裏是我想出了同時用同樣的想法實驗,用Phil Haack's post幫助。
首先,您需要擁有自己的ViewEngine才能在查看文件夾下查找文件夾。像這樣的東西(你會發現,它看起來很像菲爾哈克的區域編碼)
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
與您的自定義一個替換默認視圖引擎,在Application_Start
:
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new TestViewEngine());
現在,當你在Global.asax
確定的路線,你需要設置一個root
值,指示該文件夾尋找下查看文件夾,如下所示:
routes.MapRoute(
"ListManager",
"ListManager/{action}/{id}",
new { controller = "ListManager", action = "Index", id = "", root = "Manage" }
);
是否需要Visual Studio的設置才能在該文件夾中創建視圖,或者您希望MVC框架在查看文件夾下的文件夾中查找視圖? – 2009-05-02 01:25:37
這個問題暗示了這兩種情況,但這是由於缺乏理解,因爲我認爲創建視圖的位置會自動定義到視圖的路徑。 – BinaryMisfit 2009-05-02 07:32:10
我最終重構了網站適用於vanilla Mvc架構的方式。然而,兩個答案都爲上述問題提供了可行的解決方案。 – BinaryMisfit 2009-05-02 10:54:10