By default mvc6 searches for views of ViewComponents either in /Views/ControllerUsingVc/Components or it also looks in /views/shared folder.
Is it possible to add a custom location where it should look for them? E.g. /views/mySharedComponents
You can do that but you have to do following steps for that.
Create New View engine based on RazorViewEngine. Also by default it need Components directory so just use Views as root folder.
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;
}
}
}
}
Add ViewEngine in MVC in Startup.cs
services.AddMvc().Configure<MvcOptions>(options =>
{
options.ViewEngines.Add(Type.GetType("WebApplication10.MyViewEngine"));
});
Now I have placed My Component at following location. For example my component name is MyFirst.cshtml. So I can place Views/Components/MyFirst/Default.cshtml.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With