Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Bojan 16 posts 131 karma points
    May 14, 2016 @ 09:44
    Bojan
    1

    How to use models builder in controller, in other words, how to get strongly typed model within controller

    Hi to all,

    I want to use Umbraco models builder in the latest version 7.4.3 and I can't find any post on Google or within GitHub documentation how to "inject" my strongly typed model from models builder into a controller. I don't want to use content models directly into views. It would be good to have this example in the official documentation, instead of just saying that we can use strongly typed models everywhere, including controllers.

    I appreciate.

    Cheers, Bojan

  • Marc Goodson 1005 posts 6620 karma points MVP 4x c-trib
    May 15, 2016 @ 12:22
    Marc Goodson
    105

    Hi Bojan

    If your working with controllers in visual studio, rather than just in views; you can switch ModelsBuilder settings in the web.config to 'AppData' mode: (instead of PureLive)

    <add key="Umbraco.ModelsBuilder.Enable" value="true" />
    <add key="Umbraco.ModelsBuilder.ModelsMode" value="AppData" />
    

    Now when you generate your models, you will find in the AppData folder a 'Models folder'

    with generated c# classes representing each document type:

    Include this Models folder in your visual studio project, and you can begin to use the strongly built models inside your controllers:

    Each model has a contructor that takes an IPublishedContent so you could create a hijacked controller like so...

    public class DocTypeAliasController : RenderMvcController 
          {
             public override ActionResult Index(RenderModel model)   
             {
    var viewModel = new MyGeneratedDocTypeModel(model.Content);
            return CurrentTemplate(viewmodel);  
             }
        }
    

    but in reality you'd probably created your own custom model that inherits from the generated model to add further custom properties that you would populate in your hijacked controller...

    regards

    Marc

  • Bojan 16 posts 131 karma points
    May 15, 2016 @ 12:27
    Bojan
    0

    Hi Marc,

    Thank you very much for your detailed explanation, everything is clear now! I think this needs to be included in the official GitHub documentation, for sure.

    Happy coding, Bojan

  • John Seto 37 posts 98 karma points
    Oct 18, 2016 @ 11:45
    John Seto
    0

    I'm with you on that one.

    I found out the constructor taking a Model.Content by Intellisense!

Please Sign in or register to post replies

Write your reply to:

Draft