Tuesday, May 1, 2007

Un Documented Navigation Control using C#

Hey All,

I run into a requierment during a site creation automation at one of my customers.
In this automation we had to dynamically add links to the site's navigation only to learn that the sharepoint API for this is not what I expected.

What i needed is to do some simple things (or so i tohught) like adding header items, adding items with no link, specify links to open in new window etc...

well i came across some undocumented things that helped me do these not so simple tasks... I added here some of the code I used so it may help so of you out there.

I wanted to add navigation controls like:
· No link (href) for new navigation item (not as simple as you thing… I wanted it not to behave as a link.)
· Add a link that will open in new window
· Create a container navigation item to hold several child links
All of these are fairly simple to do using the UI, but not so simple when using code to create the links.
I did manage to control each of these features using navNode.Properties
Now, I could not find any documentation regarding how we suppose to do it, so what I had to learn myself is not documented so far anywhere I looked.

Now, with no further ado, here are some source code samples I collected:
Use this to add a container with no link:
navNode = new SPNavigationNode("Container", null, true);
navNode = CourseWeb.Navigation.QuickLaunch.AddAsLast(navNode);
navNode.Properties["UrlFragment"] = "";
navNode.Properties["NodeType"] = "Heading";
navNode.Properties["BlankUrl"] = "True";

Use this to add a link in the container:
SPNavigationNode tmpNavNode1 = new SPNavigationNode(LinkName, LinkUrl, true);
tmpNavNode1 = navNode.Children.AddAsFirst(tmpNavNode1);
tmpNavNode1.Properties["Target"] = "_blank";
SPNavigationNode tmpNavNode2 = new SPNavigationNode("Second link", "link url", true);
tmpNavNode2 = navNode.Children.AddAsLast(tmpNavNode2);
tmpNavNode2.Properties["Target"] = "_blank";//open in new window


Well, I know I spent a lot of time to find how and what to do… could it be that SharePoint team cut few corners in the API?

Anyway, hope this helps some of you developer guys,
Shai Ben Shooshan

1 comment:

Victor Ch said...

For me the following works fine, without calling Update();
SPNavigationNodeCollection nodes = web.Site.RootWeb.Navigation.QuickLaunch;
SPNavigationNode navNode = new SPNavigationNode(listTitle, listUrl, false);

foreach (SPNavigationNode node in nodes)
if (node.Title == "Lists")
SPNavigationNodeCollection chNodes = node.Children;