编程方式在SharePoint 2010顶部导航中添加链接

这里有一个简单的控制台应用程序,用对象模型添加一个链接(比如在这个例子中:一个打开SharePoint 2010中创建的子网站的链接)到父网站的顶部导航中。这是通过编程方式解决类似“在父网站的顶部导航中显示该站点”需求的一种方式。

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();
}
}
}

参考资料

Add links to Top Navigation Sharepoint 2010 programmatically

posted @ 2010-09-28 15:18  Sunmoonfire  阅读(252)  评论(0)    收藏  举报