Creating A Custom View Engine To Organise Your Pages and Block Views More Easily

Whenever I set-up a new site, I like to organise my views into a few folders...  mainly one called 'pages' and one called 'Blocks'. CustomViewEngine_Example I create my Models and ViewModels, the controller creates a folder in my 'Views' folder under 'Pages' or 'Blocks' and then go to test out the site and get the same error:


The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:

The reasons this happens is that by default MVC will look for a view with a matching name of a controller in a view folder.  In an EPi project to make your solution a lot more tidy, it's good practice to split these views up into page, blocks etc.  In order to do this you will need to create a custom class that inherits from the RazorViewEngine and adds in the 'Pages' and 'Blocks' folder, this can be done with this code snippet:

using System.Web.Mvc;

namespace Episerver.Website
{
    public class CustomViewEngine : RazorViewEngine
    {
        public CustomViewEngine()
        {
            var viewLocations = new[]
            {
                "~/Views/{1}/{0}.aspx",
                "~/Views/{1}/{0}.ascx",
                "~/Views/Shared/{0}.aspx",
                "~/Views/Shared/{0}.ascx",
                "~/Views/Pages/{1}/{0}.cshtml",
                "~/Views/Blocks/{1}/{0}.cshtml"
            };

            PartialViewLocationFormats = viewLocations;
            ViewLocationFormats = viewLocations;
        }
    }
}

The only thing left is to now register your custom view engine with MVC in your global.ascx
    public class EPiServerApplication : EPiServer.Global
    {
        protected void Application_Start()
        {
            ViewEngines.Engines.Insert(0, new CustomViewEngine());
        }
   }


Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge


Back to top
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-35662136-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();