Tuesday, March 29, 2011

Adding SPNavigationNode to current navigation programatically in SPWebEventReceiver

When I provision a site using custom site template we may want to customize the Left navigation bar. I wanted to clear out all the navigation and have My own custom static links in newly created site.

As we know we can change the navigation using UI by customizing navigation under Site Settings > Navigation > Navigation Editing and Sorting. But I am trying to do it through programatically and was able to clear out all the navigation. When I try to create a new heading and save to the site navigation, it was failing to save it.

So the trick is to get the Publishing web using PublishingWeb.GetPublishingWeb(SPWeb) before adding the navigation nodes. If you get the PublishingWeb before customizing the navigation everything seems to be working fine.

PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
publishingWeb.Navigation.CurrentNavigationNodes.AddAsFirst(new SPNavigationNode("Some Text", properties.ServerRelativeUrl
                                                                                                                                                   + "/Pages/media.aspx", false));
publishingWeb.Update();


And that did the trick to add a new navigation node with the above specified URL once the site is provisioned.

Refer this MSDN article for all sort of properties to modify navigation for a site. (http://msdn.microsoft.com/en-us/library/ee570519.aspx)