我正在开发一个可插入的 ASP.NET MVC Web 应用程序,该应用程序在运行时从区域目录中发现和注册区域。
我的问题是视图引擎找不到该区域的任何视图。
我有一个部分视图位于
~/Areas/Catalog/Views/Shared/_SearchBarPartial.cshtml
我使用以下方法设置区域:
htmlHelper.ViewContext.RouteData.DataTokens["area"] = "Catalog";
但是执行的时候
Html.Partial("_SearchBarPartial")
我收到以下错误:
未找到局部视图“_SearchBarPartial”或没有视图引擎支持搜索到的位置。搜索了以下位置:
~/Areas/Catalog/Views/Home/_SearchBarPartial.aspx ~/Areas/Catalog/Views/Home/_SearchBarPartial.ascx ~/Areas/Catalog/Views/Shared/_SearchBarPartial.aspx ~/Areas/Catalog/Views/Shared/_SearchBarPartial .ascx ~/Views/Home/_SearchBarPartial.aspx ~/Views/Home/_SearchBarPartial.ascx ~/Views/Shared/_SearchBarPartial.aspx ~/Views/Shared/_SearchBarPartial.ascx ~/Areas/Catalog/Views/Home/_SearchBarPartial。 cshtml ~/Areas/Catalog/Views/Home/_SearchBarPartial.vbhtml ~/Areas/Catalog/Views/Shared/_SearchBarPartial.cshtml ~/Areas/Catalog/Views/Shared/_SearchBarPartial.vbhtml ~/Views/Home/_SearchBarPartial.cshtml ~ /Views/Home/_SearchBarPartial.vbhtml ~/Views/Shared/_SearchBarPartial.cshtml ~/Views/Shared/_SearchBarPartial.vbhtml
我的文件夹结构是:
bin/
Areas/
Catalog/
bin/
CatalogArea.dll
Content/
Scripts/
Views/
Shared/
_SearchBarPartial.cshtml
CatalogArea.cs
Content/
Scrips/
Views/
Global.asax
要注册区域,我使用以下代码,在应用程序启动之前执行:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Bootstrapper), "LoadAreas")]
public class Bootstrapper
{
public static string ModuleDirectory
{
get { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Areas"); }
}
public static void LoadAreas()
{
var assemblyFiles = Directory.GetFiles(ModuleDirectory, "*.dll", SearchOption.AllDirectories);
assemblyFiles.ForEach(af =>
{
var assembly = Assembly.LoadFile(af);
if(assembly.GetTypes().Any(t => IsArea(t))
{
BuildManager.AddReferencedAssembly(assembly);
}
});
}
private static bool IsArea(Type t)
{
return typeof (AreaRegistration).IsAssignableFrom(t) && !t.IsAbstract;
}
}
全球.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// ...
}
}