eadam
eadam

Reputation: 26071

mvc6: specify custom location for views of viewComponents

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

Upvotes: 4

Views: 3198

Answers (4)

Andy Furniss
Andy Furniss

Reputation: 3904

You can also do the following for .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");
    })

Obviously choose AreaViewLocationFormats or ViewLocationFormats based on whether you're using Areas or not.

Upvotes: 0

Joshlo
Joshlo

Reputation: 794

I know it's an old question, but it can be done much simpler...

services.Configure<RazorViewEngineOptions>(o =>
{
     o.ViewLocationFormats.Add("/views/{0}.cshtml");
});

Upvotes: 2

STO
STO

Reputation: 10638

Basically you can do this with creating custom view engine or creating custom IViewLocationExpander

But for view components in beta-6 there will be always "Components" prefix added. Look at ViewViewComponentResult source code. And it is sad.

Good news you could create your own view component result by copying code above and replacing only formatting string for view searching.

Upvotes: 2

dotnetstep
dotnetstep

Reputation: 17485

You can do that but you have to do following steps for that.

  1. 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;                
                }
            }
    
        }
    

    }

  2. Add ViewEngine in MVC in Startup.cs

    services.AddMvc().Configure<MvcOptions>(options =>
            {              
                options.ViewEngines.Add(Type.GetType("WebApplication10.MyViewEngine"));             
    
            });
    
  3. 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.

Upvotes: 7

Related Questions