Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 762
Aximili Avatar asked Sep 05 '14 07:09

Aximili


2 Answers

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).

like image 188
Digbyswift Avatar answered Nov 20 '22 02:11

Digbyswift


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!

like image 42
Sébastien Richer Avatar answered Nov 20 '22 03:11

Sébastien Richer