PART II: Sitecore & MVC: Areas

The basic MVC functionality works pretty well in Sitecore, but there are some MVC features that do not work as expected. One of them is the use of areas. Lets do some coding  examples and find out yourself:

  1. In our project we create a new controller named “Demo”
  2. Create a new view for your Demo controller named “Index”
  3. In the new view we write some HTML: <h1>Controller: Demo – Action: Index</h1>
  4. In Sitecore create a new Controller Rendering named “DemoIndex”.
  5. Set the value of field “Controller” to “Demo”
  6. Set the value of field “Controller action” to “Index”
  7. Assign our Controller Rendering to a placeholder on a page

In this example the controller will behave as expected. Now lets add another controller, but this time we do this inside an area.

  1. In our project we create a new area named “Demo1”
  2. Inside the area we create a controller and view using the same names we did in the previous example.
  3. Add the area name to the HTML of the view so we can see the differences.
  4. In Sitecore create a new Rendering folder named “Demo1” and create a new Controller Rendering as we did in the first example.
  5. Assign our Controller Rendering to a placeholder on a page

Our application throws an exception: Multiple types where found that match the controller ‘Demo’. The reason why this exception occurs is MVC does not known anything about the area and does not know which controller it has to use. Sitecore’s solution is to provide the fully qualified type name and assembly as value in the field “Controller” of your “Controller rendering”. Lets change both Controller Renderings, set the “Controller” fields to [Controller namespace].DemoController, [Assembly name]. And refresh our page again. Yeah we got it working again…………….., but wait i was sure our views had different HTML content. Why is this page displaying the same view twice?
The problem lies in the fact that the name of the area is not specified and thus the view can not be found inside the area. A solution could be specifying the path to the view hard coded in the controller, but in my opinion it is a terrible solution. The real solution to this problem is let to MVC know in which area the controller is executing.

Expanding the Sitecore Controller Rendering Item

  1. Create a new template named “_ControllerRenderingArea”
  2. Add a section named “Data”
  3. Add a field named “Area” of type Single-Line text and make this field Shared
  4. Add our new created template to the Controller Rendering template (/sitecore/templates/System/Layout/Renderings/Controller rendering)

Now we have expanded the Sitecore Controller Rendering Item it is time to write some to make it actually work.








Leave a Reply

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