Copied to clipboard

Flag this post as spam?

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


  • Vipul 3 posts 83 karma points
    17 days ago
    Vipul
    0

    How to get multiple children from parent by ids?

    Hello,

    I am quite new to Umbraco and trying to get multiple children from parent by ids in custom api controller.

    I am manage to get all children by doing

    var content = UmbracoContext.Current.ContentCache.GetById(1114);
    var items = content.Children.Select(c => CustomModel.GetFromContent(c));
    

    Thanks,

  • Anders Bjerner 377 posts 2126 karma points MVP admin c-trib
    17 days ago
    Anders Bjerner
    0

    Hi Vipul,

    That's how I would do it as well. Perhaps add a check to see if content is null, but otherwise it looks fine ;)

    var content = UmbracoContext.Current.ContentCache.GetById(1114);
    
    if (content != null)
    {
    
        var items = content.Children.Select(c => CustomModel.GetFromContent(c));
    
    }
    
  • pranjal 61 posts 172 karma points
    15 days ago
    pranjal
    0

    To get all childrens of parent you just have to use Children property or Ancestors or descendents property which yields you all children of page

    just go to this site and link you will found all details regarding childrens.

    http://www.computermagic.gr/tutorials/umbraco-7/umbraco-data/children-of-a-page/

  • Vipul 3 posts 83 karma points
    14 days ago
    Vipul
    0

    Thanks for the quick reply, but none of above help me to resolve my issue.

    What I am trying to do is, I have custom api controller extends UmbracoApiController and GetList method to return only those children whose id is mention in parameter

    [HttpGet]
    public IEnumerable<CustomSummaryModel> GetList(int[] ids = { 1241, 1255, 1455 })
    {
        var content = UmbracoContext.Current.ContentCache.GetById(1062);
    
        var items = content.Children.Select(c => CustomSummaryModel.GetFromContent(c)); // This return all children of parent '1062'
    
        return items;
    }
    
  • Anders Bjerner 377 posts 2126 karma points MVP admin c-trib
    14 days ago
    Anders Bjerner
    100

    Hi Vipul,

    At the first statement inside the method, you're getting the content item with ID 1062. The IDs specified in the ids parameter are not used.

    Updating the code, it could look something like the code below:

    List<CustomSummaryModel> temp = new List<CustomSummaryModel>();
    
    foreach (int id in ids)
    {
    
        var content = UmbracoContext.ContentCache.GetById(id);
        if (content == null) continue;
    
        temp.AddRange(content.Children.Select(c => CustomSummaryModel.GetFromContent(c)));
    
    }
    
    return temp;
    
  • Vipul 3 posts 83 karma points
    6 days ago
    Vipul
    0

    Thanks Anders Bjerner, This is what I am looking for.

Please Sign in or register to post replies

Write your reply to:

Draft