In this tutorial, you will learn how to set-up and use a normal vanilla MVC controller with Umbraco CMS. One common usage of needing a vanilla MVC controller will crop up when you are building the header, or, footer. It is possible to build the header within the main layout file. In terms of performance and future maintainability having all the HTML within the main layout is sub-optimal.
When all the header HTML is contained within the main layout, for each and every page request al the HTML and the data required by the page will need to be generated. Instead, by moving the header HTML into its own partial and adding a caching layer will mean you can save your webserver from a load of processing, dramatically decreasing page load time and as well as increasing the number of requests a server can deal with at the same time. The code to render a normal controller is the same as a normal MVC website:
This controller would load a view within the partials folder within the 'view' folder called 'Header.cshtml'. The big issue you will encounter when trying to get a vanilla MVC site working in MVC is the routing. In normal MVC a URL is mapped to the controller and an action. In a CMS the URL is mapped to a virtual page. A controller processes many URLs for a given document type. This means if you tried to use a normal URL to access a vanilla MCV controller you would encounter a 404 error.
To prevent this you will need to register a custom route within the routing table. Within Umbraco V8 this is done using a composer and a component. The component to register a route looks like this:
A component on its own will do nothing. To ensure Umbraco processes your component you will need to register it within a custom user composer, like this:
With the composer and component installed and compiling correctly, your custom vanilla MVC controller will now load. Happy caoding!