Umbraco 7 + Razor: How to get a Document/Node by ID?
Asked Answered
P

2

8

In the sample code, this is how you get the Home page from a .cshtml file

var homePage = CurrentPage.AncestorsOrSelf(1).First();

Now, how do I get a specific page/node (not related to current page, eg. the News page) by its ID?

Protrusion answered 5/9, 2014 at 7:26 Comment(0)
R
18

You can use exactly the same approach but use .Where(x => x.Id == newsPageId).

Alternatively, you can use @Umbraco.TypedContent(newsPageId) or @Umbraco.Content(newsPageId).

Remonstrance answered 5/9, 2014 at 8:49 Comment(1)
You're right but the question specifically states Razor and a .cshtml file. If you need answer from another context, ask a question :)Remonstrance
U
8

The direct answer is Umbraco.TypedContent(id).But! If you want to get the "News" node from anywhere, I reccomend the following. Using ids is problematic for some multilingual setups and also if the id changes it will stop working.

// 1- Get root node
var site = Model.Content.AncestorOrSelf("Site");

// 2- Get news node
var news = site.Descendant("News");

This approach is more dynamic and you can now use your news node to loop it's children, or whatever you need. For this, you do need specific document types setup for Site and News types.

Hope this helps!

Unbearable answered 5/9, 2014 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.