Search code examples
umbracoumbraco7

Umbraco ModelsBuilder - How to get strongly typed objects from child nodes


I'm using Umbraco's ModelsBuilder to generate strongly typed models from my document types to use in my code.

This is working pretty well but I want to know how I can get strongly typed objects for the children of any given generated model.

Here is an example:

public ActionResult Index(HomePage model)
{
    var components = model
        .Children.Where(x => x.DocumentTypeAlias == PageComponentsFolder.ModelTypeAlias)
        .Single().Children; 
}

HomePage is a strongly typed class generated by the Umbraco model builder. Under the home page node I have a page components folder with several other nodes that all inherit from a ComponentsBaseClass.

How can I make my components variable above a strongly typed list of objects.

Is this possible?


Solution

  • Ok this is what I ended up with in the end, here is an example of how to use strongly typed models generated by the Umbraco model binder.

    var components = model.Children
        .Where(x => x.DocumentTypeAlias == PageComponentsFolder.ModelTypeAlias)
        .Single().Children; 
    
    foreach (var component in components)
    {    
        string componentNodeTypeAlias = component.DocumentTypeAlias;
    
        switch (componentNodeTypeAlias)
        {
            case SimpleHero.ModelTypeAlias:
                Html.Partial("component_simpleHero", component as SimpleHero)
                break;
    
            case VideoWithHtml.ModelTypeAlias:
                Html.Partial("component_videoWithHTML", component as VideoWithHtml)
                break;
        }
    }