Search code examples
asp.net-mvc-5asp.net-core-mvcrazorengineonion-architecturedirectory-structure

ASP.NET MVC 5 custom RazorViewEngine for multiple portal structure


I setup my MVC 5 site by category, then controller, model, view sub-folders in each category, i.e. root folder folders \Home and \Products would have these three sub-folders as well as a root \Shared\Views folder. I followed a terrific article my Matthew Renz, Clean Architecture in ASP.NET MVC 5. Done in part by creating a custom RazorViewEngine, specifically:

public CustomRazorViewEngine()
    {
        ViewLocationFormats = new string[]
        {
            "~/{1}/Views/{0}.cshtml",
        };

        PartialViewLocationFormats = new string[]
        {
            "~/Shared/Views/{0}.cshtml"
        };
    } 

There aren't many changes beyond that. I was wondering if I could build on this idea and setup a website project with a \Portals root folder and sub-folders for each Portal using some identifier (name or number) - similar to DNN. The changes to the custom razor view engine code might look some like:

public CustomRazorViewEngine()
    {
        ViewLocationFormats = new string[]
        {
            "~/Portals/{2}/{1}/Views/{0}.cshtml",
        };

        PartialViewLocationFormats = new string[]
        {
            "~/Portals/{2}/Shared/Views/{0}.cshtml"
        };
    }   

I am not sure where the values {0} and {1} come from, however. I could find a means for obtaining {2}, the portal website name. The relative paths for the rest of the site, such as \Content, \Scripts, etc. I believe I could structure myself.

The purpose for this approach is to deliver to the client a solution in which common code can be reused to support a number of portals with unique skins and features. Thank you for your time and consideration and let me know if you have any questions.

John


Solution

  • These are placeholders in the string that can be used to put the area name, controller name or action name into the string by the controller. {2} is area, {1} is controller,{0} is the action.

    You may also be interested to know that when using Asp.Net Core it's easy to get the standard Razor View Engine to locate views and such in custom locations via a ViewLocationExpander rather than needing to create a new view engine that inherits from the Razor View Engine. I only mention this because you added the asp.net-core-mvc tag on your question.

    Here is a stack overflow answer that shows how: How to specify the view location in asp.net core mvc when using custom locations?