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 305 posts 770 karma points
    1 week ago
    Marc Love
    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 380 posts 2074 karma points MVP 2x c-trib
    1 week ago
    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 305 posts 770 karma points
    1 week ago
    Marc Love
    0

    Hi Paul,

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

    Cheers,

    Marc

  • Paul Seal 380 posts 2074 karma points MVP 2x c-trib
    1 week ago
    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 305 posts 770 karma points
    1 week ago
    Marc Love
    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