Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

Add links to Top Navigation Sharepoint 2010 programmatically

Add links to Top Navigation Sharepoint 2010 programmatically

Here is a short console application to add a link (For e.g. in our case : a link to a subsite created in Sharepoint 2010) to a parent site top level navigation using object model. So its kind of a way of programmatically doing what “Display this site on the top link bar of the parent site” does.

using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;

namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using (SPSite site = new SPSite(“http://SPSite”))
{
using (SPWeb child = site.OpenWeb(“SubSite”))
{
// Verify that this is not the root of a site collection.
if (!child.IsRootWeb)
{
// Use links from parent on the child’s top link bar.
child.Navigation.UseShared = true;

// If the parent web’s top link bar is not inherited,
// add a link to the child on the parent’s top link bar.
if (!child.ParentWeb.Navigation.UseShared)
{
// Get the parent’s top link bar.
SPNavigationNodeCollection topnav = child.ParentWeb.Navigation.TopNavigationBar;

// Query for an existing link to the child.
SPNavigationNode node = topnav.Cast().FirstOrDefault(n => n.Url.Equals(child.ServerRelativeUrl));

// No link, so add one.
if (node == null)
{
// Truncate long a title.
string linkTitle = child.Title;
if (linkTitle.Length > 15)
linkTitle = linkTitle.Substring(0, 12) + “…”;

// Create the node.
node = new SPNavigationNode(linkTitle, child.ServerRelativeUrl);

// Add it.
node = topnav.AddAsLast(node);
}
}
}
}
}
Console.Write(“\nPress ENTER to continue….”);
Console.ReadLine();
}
}
}

No comments:

Post a Comment