Tuesday, April 7, 2009

Adding Top Navigation Bar programatically

Scenario:
One of my friend asked me how to add a new item to Top Navigation Bar.

Solution:
You can write a feature receiver and using Object model can update the Top Navigation Bar.

Code:

SPWeb web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
if (!web.Navigation.UseShared)
{
SPNavigationNodeCollection topNavigationNodes = web.Navigation.TopNavigationBar;

// You can also edit the Quick Launch the same way
//SPNavigationNodeCollection topNavigationNodes = web.Navigation.QuickLaunch;

SPNavigationNode objItem = new SPNavigationNode("MyWorkspace", "default.aspx", false);
topNavigationNodes.AddAsFirst(objItem);
}
web.Update();
web.AllowUnsafeUpdates = false;
Errors:
If you try to put have a absolute url , you might get an error like this
Cannot open "/http://localhost/default.aspx": no such file or folder.

Also if you miss the check for the Shared Navigation , then you will get the following error
The top link bar can only be edited for a Web site with unique navigation.

5 comments:

Unknown November 18, 2009 at 8:24 AM  

Hi,
I have problem when I update the Name and Title field of SPWeb object. TopNavigation bar doesn't get updated.
Can you tell me how to achieve this?

Sandeep November 18, 2009 at 8:33 AM  

Site Action > Site Settings > Top Navigation or Navigation and edit the Menu the way u want

Anonymous,  November 29, 2010 at 2:12 AM  

I have try using this code on several VM with no success.

I can see the topNavigationBar collection count incrementing by 1 each I run it. But the item(s) will not appear when view it either normally UI or in the navigation settings page.

Please assign.

Anonymous,  November 29, 2010 at 2:13 AM  

I have try using this code on several VM with no success.

I can see the topNavigationBar collection count incrementing by 1 each I run it. But the item(s) will not appear when view it either normally UI or in the navigation settings page.

Please assign.

Yogendra Bhardwaj April 17, 2012 at 6:07 PM  

Hi,

I have a same requirment but i want to do it from diffrent site collection with in same webapplication.

Please help