默认情况下,mvc6 在文件夹中搜索 ViewComponents 的视图,/Views/ControllerUsingVc/Components
或者也在/views/shared
文件夹中查找。是否可以在应该查找它们的位置添加自定义位置?例如/views/mySharedComponents
问问题
2612 次
4 回答
6
您可以这样做,但您必须为此执行以下步骤。
基于 RazorViewEngine 创建新的视图引擎。同样默认情况下它需要组件目录,所以只需使用视图作为根文件夹。
namespace WebApplication10 { public class MyViewEngine : RazorViewEngine { public MyViewEngine(IRazorPageFactory pageFactory, IViewLocationExpanderProvider viewLocationExpanderProvider, IViewLocationCache viewLocationCache) : base(pageFactory,viewLocationExpanderProvider,viewLocationCache) { } public override IEnumerable<string> ViewLocationFormats { get { List<string> existing = base.ViewLocationFormats.ToList(); existing.Add("/Views/{0}.cshtml"); return existing; } } }
}
在 Startup.cs 的 MVC 中添加 ViewEngine
services.AddMvc().Configure<MvcOptions>(options => { options.ViewEngines.Add(Type.GetType("WebApplication10.MyViewEngine")); });
现在我已将我的组件放置在以下位置。例如,我的组件名称是 MyFirst.cshtml。所以我可以放置 Views/Components/MyFirst/Default.cshtml。
于 2015-01-11T09:28:55.013 回答
2
基本上你可以通过创建自定义视图引擎或创建自定义IViewLocationExpander来做到这一点
但是对于 beta-6 中的视图组件,总是会添加“组件”前缀。查看ViewViewComponentResult源代码。这是可悲的。
好消息,您可以通过复制上面的代码并仅替换用于视图搜索的格式字符串来创建自己的视图组件结果。
于 2015-07-11T20:56:51.507 回答
1
我知道这是一个老问题,但它可以做得更简单......
services.Configure<RazorViewEngineOptions>(o =>
{
o.ViewLocationFormats.Add("/views/{0}.cshtml");
});
于 2018-04-17T18:28:05.060 回答
0
您还可以对.NET Core执行以下操作
services
.AddMvc(options =>
{
...
})
.AddRazorOptions(o =>
{
o.AreaViewLocationFormats.Add("Areas/{2}/Views/SUBFOLDER/{1}/{0}.cshtml");
o.ViewLocationFormats.Add("Views/SUBFOLDER/{1}/{0}.cshtml");
})
显然选择AreaViewLocationFormats
或ViewLocationFormats
基于您是否使用区域。
于 2018-11-18T23:26:47.450 回答