Question:

What's the option for calling a controller on a Sitecore MVC Layout?

Abigail: 6 days ago

Basically, I'd like to define a MVC layout in Sitecore, and have that layout be linked to both a controller and a razor file. Currently there are only options to set the Razor file, not the controller.

Goal: have the controller on the layout, set the properties that define the header and footer links. The properties are passed through to the header/footer renderings Sitecore render or MVC partial. The goal is to only call the controller once to pull the necessary data for the header and footer links, instead of twice, once in the header and footer controllers.

Example:

  • HomeController.LayoutActionResult
    • Create instance of View Model
    • Set ViewModel.Header.Info
    • Set ViewModel.Footer.Info
    • Return View(/layout/MainLayout, ViewModel)
  • Views//ayout/MainLayout.cshtml
    • stuff html
    • @Html()...(/static/path/to/header, Model.Header)
    • more html
    • @Html()...(/static/path/to/footer, Model.Footer)
    • more html

Answer:
Isla: 6 days ago

Unfortunately, this is not currently possible OOTB with Sitecore's MVC engine. Because, as you point out, for a Layout Sitecore only allows for a Razor file. And it uses that files extension to determine that it is a razor view and then uses the MVC engine.

Here is an older question asking basically the same thing (although not as elegantly worded) on regular stackoverflow: https://stackoverflow.com/questions/27006580/how-to-use-mvc-controllers-for-layours-in-sitecore

That said, as with practically anything else in Sitecore, you could probably create a new Layout template - Controller Layout, that has a Controller and Action field, like a Controller rendering. Then, using Sitecore's pipeline architecture, patch into the appropriate pipeline (most likely the httpRequestBegin) to then detect and handle your new Layout type.

In my humble opinion, it seems like a lot of work without much to gain. As, you are simply moving the logic from two separate Controller Renderings for the Header and Footer into a single controller for the Layout and should still keep the actual logic for the header and footer separated anyway.