在mvc5中使用MvcSiteMap创建面包屑

我想在mvc5中使用MvcSiteMap创建面包屑。 我在下面写了代码。 但我希望当我点击第一,第二,……他们的Id传递给View。 但它不起作用。 我做对了吗?

//Controller Name=News Home News first //id=1 second //id=2 third // id=3 About     

  [MvcSiteMapNode(Title = "News", ParentKey = "News")] public ActionResult News(int id) { ViewBag.id = id; return View(); } 

如文档中所述 ,您必须明确配置所有自定义路由参数(包括id)。 您可以通过在PreservedRouteParameters中包含键来创建与操作方法的1对1关系,也可以通过为每个路径值组合创建单独的节点来创建与该操作的1对多关系。

1对1的关系

使用XML :

  

或者使用.NET属性 :

 [MvcSiteMapNode(Title = "News", ParentKey = "News", PreservedRouteParameters = "id")] public ActionResult News(int id) { ViewBag.id = id; return View(); } 

注意:使用此方法,URL只能在SiteMapPath HTML帮助程序中正确解析,您可能需要手动修复节点的标题和可见性,如此处所述 。

1对多种关系

使用XML :

    

或者使用.NET属性 :

 [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(); } 

或使用动态节点提供程序 :

使用XML中的定义节点:

  // 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.   

或者使用.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(); } 

动态节点提供程序实现(上述两个定义节点之一所需):

 public class NewsDynamicNodeProvider : DynamicNodeProviderBase { public override IEnumerable 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; } } } }