Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling node.NiceUrl gives me # in Umbraco

Tags:

c#

.net

umbraco

Doing a project in Umbraco, and i've encountered problems in one case that when calling node.NiceUrl I get # as the result. What is weird though is that if i debug it somehow it resolves into the correct url.

var pages = Pages.Select((item, index) => new
{
    Url = item.NiceUrl,
    Selected = item.Id == currentPage.Id,
    Index = index
}).ToList();

Where Pages is obtained from:

CurrentPage.Parent.ChildrenAsList
like image 534
Mikael Gidmark Avatar asked Apr 29 '11 08:04

Mikael Gidmark


2 Answers

If I do it this way, it works, but I don't know why.

 Url = new Node(item.Id).NiceUrl,
like image 66
Mikael Gidmark Avatar answered Oct 23 '22 03:10

Mikael Gidmark


I've encountered this error and it was because the id belonged to a media node.

Media is treated differently to other content and there's no easy way of getting the url because different types of media store the url in different ways depending on context. That's why the NiceUrl function doesn't work for media (according to the umbraco developers).

My specific scenario was using images that had been selected using a media picker. I got the url via the following code. I wrapped it up in an extension method so you can consume it from a template in a convenient way.

public static string GetMediaPropertyUrl(this IPublishedContent thisContent, string alias, UmbracoHelper umbracoHelper = null)
{
    string url = "";

    if (umbracoHelper == null)
        umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

    var property = thisContent.GetProperty(alias);

    string nodeID = property != null ? property.Value.ToString() : "";

    if (!string.IsNullOrWhiteSpace(nodeID))
    {
        //get the media via the umbraco helper
        var media = umbracoHelper.TypedMedia(nodeID);

        //if we got the media, return the url property
        if (media != null)
            url = media.Url;
    }

    return url;
}
like image 3
Doctor Jones Avatar answered Oct 23 '22 01:10

Doctor Jones