I'm trying to build metadata navigation programmatically so it can be deployed in a feature event receiver and have been using the code from this MSDN page, but am unable to get a simple link to work.
The code I'm running is unmodified from the example, except that the SPSite
and SPWeb
objects are coming from the feature event receiver properties, but whenever I get to this line
NavigationTerm term1 = navTermSet.CreateTerm("Term 1", NavigationLinkType.SimpleLink);
I get an ArgumentException
with the message "The URL does not point to a page".
Which is interesting because I haven't specified a URL for the link yet!
Has anyone got this working successfully in 2013 and can see where I've gone wrong?
EDIT - Full code
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
var site = (SPSite)properties.Feature.Parent;
var web = site.RootWeb;
var webNavSettings = new WebNavigationSettings(web);
// Set basic nav settings
webNavSettings.CurrentNavigation.Source = StandardNavigationSource.TaxonomyProvider;
webNavSettings.AddNewPagesToNavigation = false;
webNavSettings.CreateFriendlyUrlsForNewPages = false;
// Set navigation term set
TaxonomySession taxonomySession = new TaxonomySession(site, true);
if (taxonomySession.TermStores.Count > 0)
{
TermStore termStore = taxonomySession.TermStores[0];
TermSet existingTermSet = termStore.GetTermSet(NavTermSetId);
if (existingTermSet != null)
{
existingTermSet.Delete();
termStore.CommitAll();
}
Group siteCollectionGroup = termStore.GetSiteCollectionGroup(site);
TermSet termSet = siteCollectionGroup.CreateTermSet("Navigation", NavTermSetId);
NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(
termSet, web, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);
navTermSet.IsNavigationTermSet = true;
navTermSet.TargetUrlForChildTerms.Value = "~site/default.aspx";
termStore.CommitAll();
NavigationTerm term1 = navTermSet.CreateTerm("Home", NavigationLinkType.SimpleLink);
term1.SimpleLinkUrl = "~site/default.aspx";
termStore.CommitAll();
}
webNavSettings.Update();
}