8

I'm trying to change the default views location so the following works:

[Route("")]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

The location of where I want the views is /MVC/Views/ControllerName/Index(MethodName)

I've attempt by adding the following to Startup => ConfigureServices (IServiceCollection)

services.Configure<RazorViewEngineOptions>(o =>
{
    o.AreaViewLocationFormats.Clear();
    o.AreaViewLocationFormats.Add("/MVC/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
});

The following works but I would prefer for it to default to the correct path

return View("/MVC/Views/Home/Index.cshtml");
1
  • are you configuring it after services.AddMvc() ? Commented Aug 7, 2018 at 10:45

2 Answers 2

11

As stated in this answer:

From .Net-Core v2.0 upwards you can use ViewLocationFormats and AreaViewLocationFormats in RazorViewEngineOptions to modify the View look-up.

The option you are looking for is ViewLocationFormats since you're not using View Areas.

Your Solution would be along these lines:

services.Configure<RazorViewEngineOptions>(o =>
    {
        o.ViewLocationFormats.Clear();
        o.ViewLocationFormats.Add("/MVC/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
        o.ViewLocationFormats.Add("/MVC/Views/Shared/{0}" + RazorViewEngine.ViewExtension);
    });

The last line is only needed if you have the shared Layouts and Paritals at that location and not in the Standard Folder.

Sign up to request clarification or add additional context in comments.

Comments

0

The accepted answer is correct, if anyone is looking for changing the default view folder location for Areas (like me), here is the solution:

services.Configure<RazorViewEngineOptions>(options =>
{
    options.AreaViewLocationFormats.Clear();
    options.AreaViewLocationFormats
        .Add($"/Path/To/Views/{{1}}/{{0}}{RazorViewEngine.ViewExtension}");
    options.AreaViewLocationFormats
        .Add($"/Path/To/Views/Shared/{{0}}{RazorViewEngine.ViewExtension}");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.