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

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *