Blog about tips & tricks for CMS enhancement

eric.petersson

Custom Razor View Engine paths for Umbraco 8


Extending your Umbraco applications to a more suitable environment with naming conventions is a good idea. Especially if you are working on a multi site setup and the default Views root from Umbraco isn't good enough to keep your project structure satisfied. Follow this simple blog post and you may add any desires path as a standard MVC View Engine location path when initializing your project.

The solution

We will listen for Umbraco 8's application initalize event which is jacked through the UmbracoApplication base class. This class may be extended at Global.asax.cs, which is associated as a code behind file for the global.asax file:

public class Global : UmbracoApplication
{
    public override void Init()
    {
        // add custom View Engine Routing for the application
        ViewEngines.Engines.Add(new CustomViewEngine());
    }
}

Update the global.asax file with reference to your web applications namespace convention instead of Umbraco's global one:

<%@ Application Codebehind="Global.asax.cs" Inherits="YourNamespaceConvention.Global" Language="C#" %>

And finally, create a class for handling your extended paths for rendering templates or views found at the default Views folder of your MVC project:

public class CustomRazorViewEngine
{
    public class CustomViewEngine : RazorViewEngine
    {
        private static readonly string[] ExtendedViewsLocations = new[] {
            "~/Views/Elements/{0}.cshtml",
            "~/Views/Templates/{0}.cshtml"
        };

        public CustomViewEngine()
        {
            ViewLocationFormats = ViewLocationFormats.Union(ExtendedViewsLocations).ToArray();
        }
    }
}

This will merge the standard MVC locations with your own set of locations.

Happy structuring!