代码之家  ›  专栏  ›  技术社区  ›  Ayo Adesina

Umbraco ModelsBuilder-如何从子节点获取强类型对象

  •  1
  • Ayo Adesina  · 技术社区  · 7 年前

    我正在使用Umbraco的ModelsBuilder从我的文档类型生成强类型模型,以便在代码中使用。

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

    2 回复  |  直到 7 年前
        1
  •  1
  •   Owen Blacker Aditya    7 年前

    IEnumerable<YourModel> childrenOfType = model.Children<YourModel>();
    

    YourModel Where() Cast<T>()

    List<ACommonType> IPublishedContent

    foreach(IPublishedContent c in collectionOfIPublishedContent)
    {
        // basic if
        if (c.DocumentTypeAlias == YourModel.ModelTypeAlias)
        {
            YourModel stronglyTypedContent = c as YourModel;
            // do some stuff
        }
    
        // or switch...
        switch (c.DocumentTypeAlias)
        {
            case YourModel.ModelTypeAlias:
                YourModel stronglyTypedContent2 = c as YourModel;
                // do a thing
                break;
        }
    
        // or use implicit casts with null checking
        YourModel stronglyTypedContent3 = c as YourModel;
        if (stronglyTypedContent3 != null)
        {
            // congrats, your content is of the type YourModel
        }
    }
    
        2
  •  0
  •   Owen Blacker Aditya    7 年前

    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;
        }
    }