Click here to Skip to main content
15,884,298 members
Articles / Web Development / ASP.NET

How to Register/Specify Custom Directories for Views in Razor ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
3.71/5 (6 votes)
19 Feb 2019CPOL3 min read 20.4K   7   2
Registering Custom Directories for Views in ASP.NET MVC

Introduction

In ASP.NET MVC by default, when we create an application, our Views reside in Views directory for our Controller actions. For example, by default it creates Home controller with Index action, and if we see in Solution Explorer in Views directory, we can see directory Views -->> Home --> Index.cshtml and we have its action like this:

C#
public class HomeController : Controller 
{ 
   public ActionResult Index() 
   { 
     return View(); 
   } 
}

and we have this action's Views in Views folder. See the following screen:

Image 1

Now by default, it will first look for Index.cshtml file in Views/Home folder and if it is unable to find it there, then it will find it in View/Shared folder, if it also does not find it there, it will throw an exception that view file is not found, here is the exception text which is thrown:

The view 'Index' or its master was not found or no view engine supports the searched locations. 
The following locations were searched:
~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

See:

Image 2

The same is the case for partial view when we call return PartialView(). It first looks in the respective controller's Views/Home directory in the case of HomeController and in case of failure, it looks in the View/Shared folder.

Using Custom Directories:

Now what if I had make a separate directory for partial views in my Views folder and Shared folder like:

Image 3

Views/Home/Partials and Views/Shared/Partial then we have to tell the ViewEngine to look in that directory as well by writing the following code in Global.asax file in Application_Start event.

For example, I have this code and I am returning _LoginPartial.cshtml from Index action of HomeController, now what will happen is it will look in View/Home directory first and in failure, it will look in View/Shared, but this time, I have my partial views in a separate directory named Partial for every controller and for shared as well, In this case HomeController partial views are in Views/Home/Partials and in Views/Shared/Partials:

C#
public class HomeController : Controller 
{ 
   public ActionResult Index() 
   { 
      return View(); 
   } 
}

In this case also, I will get the same exception as Engine will not be able to find the View file _LoginPartial.cshtml.

The beauty of ASP.NET MVC Framework is the extensiblity which you can do according to your needs and business requirements, one of them is that if you want your own directories structure for organizing your views, you can register those directories with razor view engine, doing that will make your life easy as you will not have to specify fully qualified path of the view, as razor will know that it needs to look for the view in those directories as well which you have registered with it.

So what we have to do is to register this directory pattern in the application so that every time it calls any View, it should look in those directories as well in which we have placed the View files. So here is the code for that:

C#
public class MvcApplication : System.Web.HttpApplication 
{ 
   protected void Application_Start() 
   { 
       AreaRegistration.RegisterAllAreas(); 
       WebApiConfig.Register(GlobalConfiguration.Configuration); 
       FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
       RouteConfig.RegisterRoutes(RouteTable.Routes); 
       BundleConfig.RegisterBundles(BundleTable.Bundles); 
       AuthConfig.RegisterAuth(); 

      RazorViewEngine razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().FirstOrDefault(); 
      if (razorEngine != null) 
      { 
         var newPartialViewFormats = new[] 
                                     { 
                                        "~/Views/{1}/Partials/{0}.cshtml", 
                                        "~/Views/Shared/Partials/{0}.cshtml" 
                                     }; 
        razorEngine.PartialViewLocationFormats = 
        razorEngine.PartialViewLocationFormats.Union(newPartialViewFormats).ToArray(); 
      } 
   } 
}

Now whenever we will call return PartialView("SomeView"), it will look in that Controller Views directory's subdirectory named Partials as well and in case it does not find there, it will look in both Views/Shared and Views/Shared/Partials.

Points of Interest

We saw how we can include other directories as well to be seen when getting View. In the same way, you can register other directories or your own Custom directory structure if you need to, so doing it this way, you will not need to specify the complete path for like return View("~/Views/Shared/Partials/Index.cshtml"). Instead of that, you can just write then return View() if you want to load Index View and your action name is also Index which is being called, or if you want some other view to be rendered or some other action is invoked and you want to return Index view, then you can write now return View("Index").

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
Ehsan Sajjad is a Microsoft Certified Professional, Microsoft Certified C# Specialist and he is also among the top users on StackOverflow from Pakistan with 50k+ reputation at time of writing this and counting.

He is a passionate software developer with around 5 years of professional experience in Microsoft Technologies both web and desktop applications and always open to learn new things and platforms especially in mobile application development and game development.

Some Achievements :

  • 5th Top Contributor from Pakistan on Stackoverflow.com
  • Top User in ASP.NET MVC from Pakistan on Stackoverflow.com
  • 21st June 2017 - Article of the Day - ASP.NET Community (Beginners Guide on AJAX CRUD Operations in Grid using JQuery DataTables in ASP.NET MVC 5)
  • 19th April 2017 - Article of the Day - ASP.NET Community (ASP.NET MVC Async File Uploading using JQuery)
  • March 2017 - Visual C# Technical Guru Silver Medal on Microsoft Tech Net Wiki Article Competition
  • 20 January 2017 - Article of the Day - ASP.NET Community (Async File Uploading in ASP.NET MVC)
  • 22nd September 2016 - Article of the Day - ASP.NET Community (GridView with Server Side Filtering, Sorting and Paging in ASP.NET MVC 5)
  • 22nd August 2016 - Article of the Day - ASP.NET Community (Beginners Guide for Creating GridView in ASP.NET MVC 5)
  • December 2015 - C-SharpCorner Monthly Winner

Comments and Discussions

 
GeneralThank you! Pin
K. Zimny8-Jan-16 5:02
K. Zimny8-Jan-16 5:02 
GeneralRe: Thank you! Pin
Ehsan Sajjad8-Jan-16 9:22
professionalEhsan Sajjad8-Jan-16 9:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.