正如the documentation說,你必須配置所有自定義路由參數(包括ID)明確。您可以通過將關鍵字包含在PreservedRouteParameters中來創建與操作方法的1對1關係,或者可以通過爲每個路由值組合創建一個單獨的節點,從而與該操作創建一對多關係。
1對1的關係
使用XML:
<mvcSiteMapNode title="News" controller="News" action="News" preservedRouteParameters="id"/>
或使用.NET Attributes:
[MvcSiteMapNode(Title = "News", ParentKey = "News", PreservedRouteParameters = "id")]
public ActionResult News(int id)
{
ViewBag.id = id;
return View();
}
注:使用此方法時,網址只能解決正確地在SiteMapPath HTML助手中,並且您可能需要手動修復節點的標題和可見性,如explained here。
1一對多的關係
使用XML:
<mvcSiteMapNode title="Article 1" controller="News" action="News" id="1"/>
<mvcSiteMapNode title="Article 2" controller="News" action="News" id="2"/>
<mvcSiteMapNode title="Article 3" controller="News" action="News" id="3"/>
或使用.NET Attributes:
[MvcSiteMapNode(Title = "Article 1", ParentKey = "News", Attributes = @"{ ""id"": 1 }")]
[MvcSiteMapNode(Title = "Article 2", ParentKey = "News", Attributes = @"{ ""id"": 2 }")]
[MvcSiteMapNode(Title = "Article 3", ParentKey = "News", Attributes = @"{ ""id"": 3 }")]
public ActionResult News(int id)
{
ViewBag.id = id;
return View();
}
或使用Dynamic Node Provider:
隨着XML定義節點:
<mvcSiteMapNode title="News" controller="News" action="Index" key="News">
// Setup definition node in XML (won't be in the SiteMap)
// Any attributes you put here will be the defaults in the dynamic node provider, but can be overridden there.
<mvcSiteMapNode dynamicNodeProvider="MyNamespace.NewsDynamicNodeProvider, MyAssembly" controller="News" action="News"/>
</mvcSiteMapNode>
,或者在.NET定義節點屬性:
// Setup definition node as a .NET Attribute (won't be in the SiteMap)
// Any properties you put here will be the defaults in the dynamic node provider, but can be overridden there.
[MvcSiteMapNode(DynamicNodeProvider = "MyNamespace.NewsDynamicNodeProvider, MyAssembly")]
public ActionResult News(int id)
{
ViewBag.id = id;
return View();
}
動態節點提供程序實現(對於上述2個定義節點的所需):
public class NewsDynamicNodeProvider
: DynamicNodeProviderBase
{
public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
{
using (var db = new EnityContext())
{
// Create a node for each news article
foreach (var news in db.News)
{
var dynamicNode = new DynamicNode();
dynamicNode.Title = news.Title;
dynamicNode.ParentKey = "News";
dynamicNode.RouteValues.Add("id", news.Id);
yield return dynamicNode;
}
}
}
}