我只在单个项目区域尝试过这种方法。因此,如果有人在多项目领域解决方案中尝试了这一点,请告诉我们。在单个项目区域维护视图的解决方案
区域支持已添加到MVC2。但是,您的控制器的视图必须位于主视图文件夹中。我在这里提出的解决方案将允许您在每个区域保留特定区域的视图。如果您的项目结构如下所示,博客是一个区域。
+ Areas <-- folder
+ Blog <-- folder
+ Views <-- folder
+ Shared <-- folder
Index.aspx
Create.aspx
Edit.aspx
+ Content
+ Controllers
...
ViewEngine.cs
将此代码添加到Global.asax.cs中的Application_Start方法中。它会清除您当前的视图引擎,并使用我们的新ViewEngine。
// Area Aware View Engine
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new AreaViewEngine());
然后创建一个名为ViewEngine.cs的文件并添加下面的代码。
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
namespace MyNamespace
{
public class AreaViewEngine : WebFormViewEngine
{
public AreaViewEngine()
{
// {0} = View name
// {1} = Controller name
// Master Page locations
MasterLocationFormats = new[] { "~/Views/{1}/{0}.master"
, "~/Views/Shared/{0}.master"
};
// View locations
ViewLocationFormats = new[] { "~/Views/{1}/{0}.aspx"
, "~/Views/{1}/{0}.ascx"
, "~/Views/Shared/{0}.aspx"
, "~/Views/Shared/{0}.ascx"
, "~/Areas/{1}/Views/{0}.aspx"
, "~/Areas/{1}/Views/{0}.ascx"
, "~/Areas/{1}/Views/Shared/{0}.aspx"
, "~/Areas/{1}/Views/Shared/{0}.ascx"
};
// Partial view locations
PartialViewLocationFormats = ViewLocationFormats;
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
return new WebFormView(partialPath, null);
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
return new WebFormView(viewPath, masterPath);
}
} // End Class AreaViewEngine
} // End Namespace
这将找到并使用您在您所在地区创建的视图。
这是一种可能的解决方案,允许我在指定区域保留视图。其他人是否有不同的,更好的增强型解决方案?
谢谢
在“区域”文件夹中使用“添加区域”时,会在新区域下创建“视图”子文件夹。你确定你没有错过什么吗? – 2010-02-02 22:55:40
你是对的,它会创建一个Views文件夹。但是,这些视图必须位于要找到的主项目的视图文件夹中。请参阅http://forums.asp.net/p/1494640/3540105.aspx,首先回答这个问题。 – 37Stars 2010-02-02 23:05:34
+1嗯,你的方法是健全的。事实上,我无法想象为什么MVC的人没有在主版本中包含额外的路径。没有意义。 – 2010-02-02 23:23:22