Back up

Code Pharaoh

Redirecting a node to parent page with anchor in Umbraco

#Umbraco #c# #snippet

A project i worked on recently needed to have a page made up of individual content nodes. Normally I would use Archetype to build a page like this, however, an extra requirement was that these nodes could be 'picked' elsewhere in the site and used to build content for other pages. Each of the nodes on these pages would then have a link back to the their original parent page. 

In the past I might have created a view or controller with logic to redirect the user to the parent page attaching an # anchor variable to direct the visitor to the correct page of the parent page. However I using IUrlProvider opens up a much nicer way around this.

 

namespace YOURPROJECTNAMESPACE.Core.UrlProviders
{
    public class CustomNodeProvider : IUrlProvider
    {
        public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode)
        {
            var content = umbracoContext.ContentCache.GetById(id);
            if (content != null && content.DocumentTypeAlias == "DOC TYPE ALIAS FOR YOUR NODE" && content.Parent != null)
            {
                return content.Parent.Url+"#anchor-"+content.Id;
            }

            return null;
        }
        public IEnumerable<string> GetOtherUrls(UmbracoContext umbracoContext, int id, Uri current)
        {
            return Enumerable.Empty<string>();
        }

    }
    public class ApplicationStartUp : ApplicationEventHandler
    {
        protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            UrlProviderResolver.Current.InsertTypeBefore<DefaultUrlProvider, ContributorClipProvider>();
        }
    }
}

 

Now when these nodes are linked to they return a URL similar to /parentpage#anchor-1234 Problem solved. You can read more about this at 24 days in Umbraco http://24days.in/umbraco/2014/urlprovider-and-contentfinder/