Copied to clipboard

Flag this post as spam?

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


  • Marc Love (uSkinned.net) 432 posts 1691 karma points
    Sep 09, 2019 @ 15:54
    Marc Love (uSkinned.net)
    0

    Access IContent in class file

    How do you access IContent in a class in Umbraco 8?

    I can access IPublishedContent no bother using dependency injection:

    private readonly IUmbracoContextFactory _context;
    
    public MyController(IUmbracoContextFactory context)
    {
        _context = context;
    }
    
    public MyMethod(int currentNodeID)
    {
       using (var cref = _context.EnsureUmbracoContext())
       {
          var cache = cref.UmbracoContext.Content;
          var currentNode = cache.GetById(currentNodeID);
        }
    }
    

    Just dont have a clue how to get IContent.

  • Paul Seal 524 posts 2889 karma points MVP 6x c-trib
    Sep 09, 2019 @ 16:22
    Paul Seal
    100

    Hi Marc

    Have you tried this:

    using System.Web.Mvc;
    using Umbraco.Core.Models;
    using Umbraco.Core.Services;
    
    namespace Umbraco814
    {
        public class MyController
        {
            private IContentService _contentService;
    
            public MyController(IContentService contentService)
            {
                _contentService = contentService;
            }
    
            public ActionResult MyMethod(int currentNodeID)
            {
                IContent currentNode = _contentService.GetById(currentNodeID);
                return null;
            }
        }
    }
    

    I got this working in a class library with UmbracoCms.Core and UmbracoCms.Web nuget packages installed.

    Cheers

    Paul

  • Marc Love (uSkinned.net) 432 posts 1691 karma points
    Sep 10, 2019 @ 12:24
    Marc Love (uSkinned.net)
    0

    Hi Paul,

    Thanks for that, I must have had a brain freeze for not trying that.

    Cheers,

    Marc

  • Paul Seal 524 posts 2889 karma points MVP 6x c-trib
    Sep 10, 2019 @ 12:50
    Paul Seal
    0

    Hi Marc

    I got a notification on email that you asked about Descendants and Ancestors.

    You can use the content service like this:

    IContent currentNode = _contentService.GetById(currentNodeID);
    IEnumerable<IContent> ancestors = _contentService.GetAncestors(currentNode);
    IEnumerable<IContent> descendants = _contentService.GetPagedDescendants(currentNodeID, 0, 10, out long totalRecords);
    

    Cheers

    Paul

  • Marc Love (uSkinned.net) 432 posts 1691 karma points
    Sep 10, 2019 @ 13:05
    Marc Love (uSkinned.net)
    0

    Hi Paul,

    Yes, I deleted the question as I figured it out, thanks for the info.

    Cheers,

    Marc

Please Sign in or register to post replies

Write your reply to:

Draft