My Asp.Net Core project is arranged as follows:
MyApp
--Folder1
Folder1Controller.cs
Index.cshtml
--Folder2
Folder2Controller.cs
Index.cshtml
--Views
Shared
etc..
I've changed the startup, so that it's aware of this directory structure:
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationFormats.Clear();
options.ViewLocationFormats.Add($"/Folder1/{{0}}{RazorViewEngine.ViewExtension}");
options.ViewLocationFormats.Add($"/Folder2/{{0}}{RazorViewEngine.ViewExtension}");
options.ViewLocationFormats.Add($"/Views/Shared/{{0}}{RazorViewEngine.ViewExtension}");
});
The code for the Folder1Controller
looks like this:
public IActionResult Index()
{
return View();
}
And it works fine. However, the code for Folder2Controller
looks exactly the same. The problem is that when it executes the Index()
method for Folder2
it looks in Folder1
first. I can get around it by doing this:
public IActionResult Index(string id)
{
return View("/Folder2/Index.cshtml");
}
My question is, is there a way to get Asp.Net Core to look in the current directory first? Even if I use a relative path ( "./Index"
), it still goes to Folder1
first.
You can add a folder named with controller name to your folder1,folder2,so that route can recognize which view to find.
Firstly,change the folder structure like this:
MyApp
--Folder1
Folder1Controller.cs
--Folder1
Index.cshtml
--Folder2
Folder2Controller.cs
--Folder2
Index.cshtml
--Views
Shared
etc..
Startup:
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationFormats.Clear();
options.ViewLocationFormats.Add("/Folder1/{1}/{0}" + RazorViewEngine.ViewExtension);
options.ViewLocationFormats.Add("/Folder2/{1}/{0}" + RazorViewEngine.ViewExtension);
options.ViewLocationFormats.Add($"/Views/Shared/{{0}}{RazorViewEngine.ViewExtension}");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.