Copied to clipboard

Flag this post as spam?

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


  • andrew shearer 417 posts 525 karma points
    1 week ago
    andrew shearer
    0

    Umbraco context in ViewComponent: best practice

    Hi everyone

    Partials don’t exist in the .net core world, now its all about View Components. So If my scenario was having a “header” View Component in my Layout file (so its shared across all site templates), and the menu shown in this header was managed on a “homepage” node in the CMS, what would be the best way of obtaining this property for the viewModel? i.e. this in my umbraco 8 site:

    @Html.Action("Header", "MyController")
    

    becomes this in umbraco 9:

    <vc:header />
    

    Do I use dependency injection to give it some Umbraco Context? https://our.umbraco.com/documentation/reference/using-ioc/ hasn’t been updated for umbraco 9 so haven’t found a good example for doing this yet.

    Or can I access the ModelsBuilder classes somehow? i.e. the homepage model and the “menu” property from that

    Or another better method?

    Thanks

    Andrew

  • Benjamin Carleski 29 posts 246 karma points MVP c-trib
    1 week ago
    Benjamin Carleski
    1

    Yes, you can use dependency injection. According to the Microsoft Docs, all view components can use dependency injection in the constructor, so you would inject an Umbraco Context just like you would in any other location. You'd have a constructor argument of type IUmbracoContextAccessor, and then save that to a private, readonly field. Then in your InvokeAsync method, you would get the Umbraco Context from the accessor field and use it to get your homepage node. You could cast the IPublishedContent for the home page node to the Models Builder type to make it simpler to access the properties you needed, or you could use the .Value method on IPublishedContent. Something like the following should work:

    public class MyViewComponent : ViewComponent
    {
        private readonly IUmbracoContextAccessor _umbracoContextAccessor;
    
        public MyViewComponent(IUmbracoContextAccessor umbracoContextAccessor)
        {
            _umbracoContextAccessor= umbracoContextAccessor;
        }
    
        public async Task<IViewComponentResult> InvokeAsync()
        {
            var ctx = _umbracoContextAccessor;
            var home = ctx.Content.GetAtRoot().FirstOrDefault() as Homepage;
            var menu = home?.Menu;
            return View(menu);
        }
    }
    
  • andrew shearer 417 posts 525 karma points
    1 week ago
    andrew shearer
    0

    thanks Benjamin! yes it was the IUmbracoContextAccessor documentation that i couldn't find. thank you

Please Sign in or register to post replies

Write your reply to:

Draft