我只在单个项目区域中尝试过。因此,如果有人在多项目区域解决方案中尝试此操作,请告诉我们。
区域支持已添加到 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
这将找到并使用您在您的区域中创建的视图。
这是一种可能的解决方案,允许我将视图保留在指定区域。还有其他人有不同的、更好的、增强的解决方案吗?
谢谢