lamarant lamarant - 1 year ago 65
ASP.NET (C#) Question

Adding sub-directory to "View/Shared" folder in ASP.Net MVC and calling the view

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):


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:


Thanks for the help!

Answer Source

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.

public class RDDBViewEngine : RazorViewEngine
    private static readonly string[] NewPartialViewFormats = 

    public RDDBViewEngine()
        base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();


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:

ViewEngines.Engines.Add(new RDDBViewEngine()); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download