user3833046
user3833046

Reputation: 53

Is there a way to modify sitemap node attributes at run-time?

I am wondering if there's a way to change the content of a sitemap while the application is running and automatically update the application accordingly?

Example: I want to change the URL of particular node.

I am using MVC SiteMap Provider, though maybe it does not matter what provider are you using as long as it pertains to sitemap.

Upvotes: 1

Views: 2130

Answers (1)

NightOwl888
NightOwl888

Reputation: 56869

Certain properties are request-writable at runtime. This means you can update them for the current request, but the value will not carry over from one request to the next. Those properties are (as of v4.6.7):

  • Order
  • Title
  • Description
  • TargetFrame
  • ImageUrl
  • ImageUrlProtocol
  • ImageUrlHostName
  • VisibilityProvider
  • Clickable
  • UrlResolver
  • Protocol
  • HostName
  • CanonicalUrl
  • CanonicalKey
  • CanonicalUrlProtocol
  • CanonicalUrlHostName
  • Route
  • Attributes
  • RouteValues

You can write these values by calling one of the "find" methods (or use the current node property) to get a reference to a node and then updating the property directly.

var currentNode = MvcSiteMapProvider.SiteMaps.Current.CurrentNode;
var parentNode = null;

// Current node will be null on any page that is not in the sitemap (or configured incorrectly to match)
if (currentNode != null)
{
    parentNode =  = currentNode.ParentNode;
}

// Parent node will be null if the current node is the root node
// or is null.
if (parentNode != null)
{
    parentNode.Description = "Some Parent Node";
}

The purpose of the SiteMap is to maintain the relationships between different URLs so changing the URL at runtime defeats its purpose somewhat. After all, the relationship may no longer be valid if the URL changes but the node does not change position in the hierarchy.

However, you can add nodes dynamically using dynamic nodes or by implementing ISiteMapNodeProvider in order to create nodes based on dynamic data. Additionally, you can force the SiteMap to rebuild immediately by using the SiteMapCacheReleaseAttribute on each of the actions that updates the data.

You can also fake breadcrumbs by using preservedRouteParameters as described in How to Make MvcSiteMapProvider Remember a User's Position - Forcing a Match. This will make a specific node always match every value for the specified route values (for example "id"), so the node will effectively match more than one URL. You can then fix the title and the visibility of the node as described in the linked article.

Upvotes: 1

Related Questions