我只在单个项目区域尝试过这个。因此,如果有人在多项目区域解决方案中尝试此操作,请告诉我们。
区域支持已添加到MVC2。但是,控制器的视图必须位于主视图文件夹中。我在这里提出的解决方案将允许您在每个区域保留您的区域特定视图。如果你的项目结构如下,那么Blog就是一个区域。
+ 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
这将查找并使用您在所在区域中创建的视图。
这是一种可能的解决方案,允许我在指定区域保持视图。还有其他人有不同的,更好的,增强的解决方案吗?
由于
答案 0 :(得分:2)
我很遗憾成为那个告诉你的人,但你必须遗漏一些东西。我目前使用ASP.NET MVC 2 RC开箱即用。
我假设您拥有所有注册路由,并且在您所在区域的视图文件夹中包含正确的web.config文件?
也许看看this walk through,特别是有关创建区域的部分。
HTHS,
查尔斯
编辑:
好的,所以你不喜欢投入额外的new { area = "blog' }, null
- 公平地说,我会承认它的傻瓜......但是你还要做什么呢?
当你有两个同名的控制器时会发生什么?一个在你的根项目中,一个在一个区域中,还是两个控制器在两个不同的区域中具有相同的名称?如何找到正确的观点?
此外,我确实发现您的ViewLocationFormats
存在问题。所有区域视图位置都没有参考其区域...例如~/Areas/{1}/Views/{0}.ascx
- 它如何知道哪个区域?
如果您建议将所有不同区域的视图全部放入其控制器名称下的Areas
文件夹中,然后在Views
和Views/Shared
下找到 - 我强烈推荐......它会很快变得一团糟。
那么你离开了哪里?在创建路线时,您确实需要指定区域。它真的归结为这样一个事实:虽然它必须指定区域,但实际上没有别的办法。
答案 1 :(得分:0)
此解决方案在Mvc2中运行良好。在Mvc3中没有必要。