Custom View Components Folder configuration

209 views Asked by At

Using Net.Core 7 I have a few View Components which are located in:

/Pages/Components/Component1/Default.cshtml
/Pages/Components/Component2/Default.cshtml
...

I want to place all views in Components folder and use the Component's name:

/Pages/Components/Component1.cshtml
/Pages/Components/Component2.cshtml
...

I was able to change the name from Default to Component1 using:

public IViewComponentResult Invoke() {

  return View("Component1");

} 

Can this be accomplish with a global configuration?

What about placing all in Components folder and not using one folder per component?

1

There are 1 answers

0
MD Zand On

You can use RazorViewEngineOptions e.g.

builder.Services.AddControllersWithViews();
builder.Services.Configure<RazorViewEngineOptions>(o =>
{
    o.ViewLocationFormats.Clear(); //Or just add another
    o.ViewLocationFormats.Add
("/Components/{0}" + RazorViewEngine.ViewExtension);
   
});

Be careful about o.ViewLocationFormats.Clear() it may make the other mvc controllers not work