Press Ctrl / CMD + C to copy this to your clipboard.
This post will be reported to the moderators as potential spam to be looked at
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:
becomes this in umbraco 9:
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?
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)
public async Task<IViewComponentResult> InvokeAsync()
var ctx = _umbracoContextAccessor;
var home = ctx.Content.GetAtRoot().FirstOrDefault() as Homepage;
var menu = home?.Menu;
yes it was the IUmbracoContextAccessor documentation that i couldn't find. thank you
is working on a reply...
Write your reply to:
Image will be uploaded when post is submitted