logikfabrik

The Umbraco 8 Models Builder and strongly-typed route hijacking

2 min read

The Models Builder is a tool that generates strongly-typed models for your content types. The Models Builder is enabled by default, and models are generated and compiled in memory, at runtime. This mode is called PureLive, and it’s a good fit if you build and maintain your site using the backoffice.

There are other modes.

If your site uses route hijacking, modes AppData and LiveAppData are more fitting. For AppData and LiveAppData models are generated and saved to App_Data/Models, but not compiled.

Include the generated files in your VS project, and you’ll be able to strongly-type your controllers.

You strongly-type a controller by going from A) to B):

A)

namespace Logikfabrik.Umbraco.Controllers
{
  using System.Web.Mvc;
  using global::Umbraco.Web.Models;
  using global::Umbraco.Web.Mvc;

  public class NewsPageController : RenderMvcController
  {
    public override ActionResult Index(ContentModel model)
    {
      return CurrentTemplate(model);
    }
  }
}

B)

namespace Logikfabrik.Umbraco.Controllers
{
  using System.Web.Mvc;
  using global::Umbraco.Web.Models;
  using global::Umbraco.Web.Mvc;
  using global::Umbraco.Web.PublishedModels;

  public class NewsPageController : RenderMvcController
  {
    public ActionResult Index(ContentModel<NewsPage> model)
    {
      return CurrentTemplate(model);
    }
  }
}

For this example, I created a document type News Page, and a controller to go with it. For A) I used the Models Builder mode PureLive. For B) I used LiveAppData. I included the generated file App_Data/Models/NewsPage.generated.cs in my VS project, and changed ContentModel to ContentModel<NewsPage>.

And that’s it.