SiteMapNode is readonly, property 'Url' cannot be modified

时间:2016-04-04 16:38:53

标签: asp.net-mvc asp.net-mvc-sitemap

I setup MVC breadcumbs for my website using MvcSiteMapProvider (Nuget package MvcSiteMapProvider.MVC5 (version 4.6.22)).

It works fine.

Then I want to update Url of Sitemap dynamically like:

SiteMaps.Current.CurrentNode.Url = Url.Action("Index");

Then I got this error:

SiteMapNode is readonly, property 'Url' cannot be modified

Note that I am still able to update Title:

SiteMaps.Current.CurrentNode.Title = "/Index";

Any idea?

1 个答案:

答案 0 :(得分:1)

The SiteMap is a statically cached object that is shared between all users. Technically, all of the properties are read-only at runtime. However, some of the properties (such as Title) are request-cached so you can safely update them at runtime without affecting other users.

The Url property is a special property that dynamically builds the URL through the MVC UrlHelper class (which is directly driven from your routes). It makes no sense to set it to Url.Action("Index") because that is effectively what it does just by itself (unless you are using a dynamic node provider or custom ISiteMapNodeProvider - those are startup extension points where you load the node configuration, so the properties are read-write).

You just need to set the correct controller and action in your node configuration (which could be XML, attribute based, or code based) and the URL will resolve on its own.

XML Example

<mvcSiteMapNode title="Projects" controller="Project" action="Index"/>

NOTE: You need to account for all route values in the request, either by adding them as another attribute myId="123" or by using preservedRouteParameters="myId" (which tells it to include the myId from the current request when building the URL). See this article for a detailed description of using these options.

NOTE: Setting a URL in the SiteMap configuration effectively overrides MVC support for that node. So, you shouldn't set a URL at all unless it is a non-MVC URL.

相关问题