MVC 3 is amazing. I love how it’s working and how developpers are able to enhance its behavior.
When you’re building an ASP.NET MVC3 project, you work with views. To organize and share view’s part, you can use partial view. (Or Editor Template but it’s not today’s subject).
Often, partial’s views are placed into the View folder and editor template in the Shared/EditorsTemplate folder.

Partial View in View/Module Folder

Partial View in View/Shared Folder
But when you want to correctly separate View and Partial view, you want to reorganize folder. And that’s where the problem is. Razor tries to find a partial view in a predefined location’s list.
If the parent page is in the Module “Home” and the partial view name is “_MyPartial”, Razor will search the partial view in different folder:
- The /Views/Home folder a file named “_MyPartial” (With aspx, ascx, cshtml or vbhtml extension).
- The View/Shared folder a file named “_MyPartial” (With aspx, ascx, cshtml or vbhtml extension).
Okay so we don’t have a lot of choice. If the Partial is shared between modules, the View/Shared folder is perfect. But if the view is just called by the Home module, I want to create a subfolder into this module to include all my partial view.
So, how could we say to Razor: “Please, find my partial view in the /View/Home/Partial folder”?
Two solutions are available:
- When you call the partial view in the parent view, just change the path to the partial view …
Replace
@Html.Partial("_MyPartial")
By
@Html.Partial("Partial/_MyPartial")
This is the simplest solution but, on my opinion, we remove the intelligence of Razor to find the partial view on his own.
- You can override Razor’s predefined path to find partial views.
The procedure is simple :
First, create a class with RazorViewEngine as its base class and add your view locations.
RozorViewEngine class has a property named PartialViewLocationFormats where you can find all the location used by Razor to find the partial view. So we just need to add location format in this list and …that’s all !
public class MyViewEngine : RazorViewEngine
{
public MyViewEngine()
{
var newLocationFormat = new[]
{
"~/Views/{1}/Partial/{0}.cshtml",
};
PartialViewLocationFormats = PartialViewLocationFormats.Union(newLocationFormat).ToArray();
}
}
About the location format, remember that {0} is the ViewName and {1} the module name.
The last thing to do is to register your custom view engine in the Razor ViewEngines collection.
In the Application_Start method of the Global.asax, just add this line :
protected void Application_Start()
{
ViewEngines.Engines.Add(new MyViewEngine());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
So, now you can add your partial view in the View/Home/Partial folder and call normaly your partial view.



very fantastic. i was exactly looking for such solution
Brilliant, just what I was looking for! Thanks.