Create Top Navigation Link in SharePoint using CSOM

The example in this topic show how to use CSOM to Create Top Navigation Link in SharePoint

  • using Microsoft.SharePoint.Client;
  • using System.Linq;
  •  
  • using (ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection"))
  • {
  • NavigationNodeCollection topNavigationCollection = null;
  •  
  • // Option 1: This will get quick launch collection from parent web
  • // This option will work only if the method is running from sub-site otherwise parent ID will be Null
  • clientcontext.Load(clientcontext.Web.ParentWeb, p => p.Id);
  •  
  • clientcontext.ExecuteQuery();
  • topNavigationCollection = clientcontext.Site.OpenWebById(clientcontext.Web.ParentWeb.Id).Navigation.TopNavigationBar;
  •  
  • // Option 2: This will get quick launch collection from current site
  • topNavigationCollection = clientcontext.Web.Navigation.TopNavigationBar;
  •  
  • clientcontext.Load(clientcontext.Web);
  • clientcontext.ExecuteQuery();
  •  
  • NavigationNodeCreationInformation nodeCreation = new NavigationNodeCreationInformation();
  • nodeCreation.Title = "Node name";
  • nodeCreation.Url = "Node URL";
  •  
  • // Option 1: This will add the new node at the last position in Node collection
  • // If this is not defined (not set to true), the node will be created at the first position else the node will be created at the last position
  • nodeCreation.AsLastNode = true;
  •  
  • // Option 2: Using Previous node.
  • clientcontext.Load(topNavigationCollection);
  • clientcontext.ExecuteQuery();
  • NavigationNode newNode = topNavigationCollection.FirstOrDefault();
  • clientcontext.Load(newNode);
  • clientcontext.ExecuteQuery();
  •  
  • // Here "Previous navigation" will act as a previous node and the new node will be created after that
  • NavigationNode prevnode = topNavigationCollection.Where(Node => Node.Title == "Node Title/Name").FirstOrDefault();
  • nodeCreation.PreviousNode = prevnode;
  •  
  • // Adds the new navigation node to the collection
  • topNavigationCollection.Add(nodeCreation);
  •  
  • clientcontext.Load(topNavigationCollection);
  • clientcontext.ExecuteQuery();
  • }

Thank you for reading this article. This code was tested in SharePoint 2013

We value your feedback:

Page URL:

Name:

 

Email:

 
 

Feedback:

 

© 2019 Code SharePoint