在ASP.NET MVC中定义更多"共享"文件夹

Owe*_*wen 1 asp.net-mvc partial-views asp.net-mvc-4

是否可以为ASP.NET MVC定义更多文件夹以搜索视图或部分?

例如,如果我浏览到/ home /索引和索引操作返回查看(),ASP.NET MVC将着眼于以下地点:

  • 〜/浏览/首页/的Index.aspx
  • 〜/浏览/首页/ Index.ascx
  • 〜/查看/共享/的Index.aspx
  • 〜/查看/共享/ Index.ascx
  • 〜/浏览/首页/ Index.cshtml
  • 〜/浏览/首页/ Index.vbhtml
  • 〜/查看/共享/ Index.cshtml
  • 〜/查看/共享/ Index.vbhtml

我想创建另一个文件夹,比如〜/ Views/PartivalViews /,将被搜索.

显然,我正在寻找这种存储我的PartialViews的整洁方式.

Dar*_*rov 5

您可以编写一个custom view engine可以指定其他文件夹的位置,ASP.NET MVC将在其中查找视图.

这里的想法是编写一个类RazorViewEngine,从其构造函数集中派生出各种属性,例如:

  • AreaViewLocationFormats
  • AreaMasterLocationFormats
  • AreaPartialViewLocationFormats
  • ViewLocationFormats
  • MasterLocationFormats
  • PartialViewLocationFormats

以下是您可以随意覆盖的默认值:

public RazorViewEngine(IViewPageActivator viewPageActivator) : base(viewPageActivator)
{
    base.AreaViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/{1}/{0}.vbhtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.vbhtml" };
    base.AreaMasterLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/{1}/{0}.vbhtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.vbhtml" };
    base.AreaPartialViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/{1}/{0}.vbhtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.vbhtml" };
    base.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml", "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml" };
    base.MasterLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml", "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml" };
    base.PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml", "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml" };
    base.FileExtensions = new string[] { "cshtml", "vbhtml" };
}
Run Code Online (Sandbox Code Playgroud)

然后只需在以下位置注册自定义视图引擎Application_Start:

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MyRazorViewEngine());
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我在注册自定义引擎之前删除了所有其他默认视图引擎(WebForms和Razor).