I'm currently developing a site using ASP.Net MVC3 with Razor. Inside the "View/Shared" folder, I want to add a subfolder called "Partials" where I can place all of my partial views (for the sake of organizing the site better.
I can do this without a problem as long as I always reference the "Partials" folder when calling the views (using Razor):
@Html.Partial("Partials/{ViewName}")
My question is if there is a way to add the "Partials" folder to the list that .Net goes through when searching for a view, this way I can call my view without having to reference the "Partials" folder, like so:
@Html.Partial("{ViewName}")
Thanks for the help!
I've updated lamarant's excellent answer to include Areas:
Then don't forget to include in your application start:
You can create register your own view engine that derives from whatever view engine your are using (Webforms/Razor) and specify whatever locations you want in the constructor or just add them to the list of already existing locations:
Then in application start you would add your view engine like so:
ViewEngines.Engines.Add(new MyViewEngineWithPartialPath());
Solved this. To add the "Shared/Partials" sub directory I created to the list of locations searched when trying to locate a Partial View in Razor using:
First create a view engine with RazorViewEngine as its base class and add your view locations as follows. Again, I wanted to store all of my partial views in a "Partials" subdirectory that I created within the default "Views/Shared" directory created by MVC.
Note that {1} in the location format is the Controller name and {0} is the name of the view.
Then add that view engine to the MVC ViewEngines.Engines Collection in the Application_Start() method in your global.asax:
Thank you for your answers. This has organized my Shared folder, but why do you create a new type of view engine? I just made a new
RazorViewEngine
, set it'sPartialViewLocationFormats
and added it to the list ofViewEngines
.You can also update the partialview-location-formats of the registered RazorViewEngine. Place the below code in Application_Start in Global.asax.
If you are doing this in ASP.NET Core, simple go to the Startup class, under
ConfigureServices
method, and put