当前无法在使用 MvcSiteMapNodeAttribute 时将“静态”节点添加到动态节点。但是,您可以直接在 IDynamicNodeProvider 实现中添加“静态”节点(即数据驱动节点的子节点)。
public class PeopleDynamicNodeProvider
: DynamicNodeProviderBase
{
public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
{
using (var db = new MyContext())
{
// Create a node for each album
foreach (var person in db.People)
{
string personKey = "Person_" + person.Id.ToString();
DynamicNode dynamicNode = new DynamicNode();
dynamicNode.Key = personKey;
dynamicNode.Title = person.Name;
dynamicNode.ParentKey = "People"; // Attach to a node that is defined somewhere else
dynamicNode.RouteValues.Add("id", person.Id.ToString());
yield return dynamicNode;
DynamicNode staticNode = new DynamicNode();
staticNode.Title = person.Name + " Details";
staticNode.ParentKey = personKey;
staticNode.Controller = "People";
staticNode.Action = "Details";
staticNode.RouteValues.Add("id", person.Id.ToString());
yield return staticNode;
}
}
}
}
如果你真的必须使用 MvcSiteMapNodeAttribute 来定义它们,你可以将上面分成 2 个独立的动态节点提供者,然后在一个属性上声明第二个。
由于多次调用数据库的额外开销,这会慢很多。您可以通过请求缓存您的人员数据来解决这个问题,以便在提供者之间共享。
public class PeopleDynamicNodeProvider
: DynamicNodeProviderBase
{
public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
{
using (var db = new MyContext())
{
// Create a node for each album
foreach (var person in db.People)
{
string personKey = "Person_" + person.Id.ToString();
DynamicNode dynamicNode = new DynamicNode();
dynamicNode.Key = personKey;
dynamicNode.Title = person.Name;
dynamicNode.ParentKey = "People"; // Attach to a node that is defined somewhere else
dynamicNode.RouteValues.Add("id", person.Id.ToString());
yield return dynamicNode;
}
}
}
}
public class PeopleDetailsDynamicNodeProvider
: DynamicNodeProviderBase
{
public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
{
using (var db = new MyContext())
{
// Create a node for each album
foreach (var person in db.People.Where(x => x.PersonCategoryId == node.Key))
{
string personKey = "Person_" + person.Id.ToString();
DynamicNode staticNode = new DynamicNode();
staticNode.Title = person.Name + " Details";
staticNode.Key = person.PersonCategoryId;
staticNode.ParentKey = personKey;
staticNode.Controller = "People";
staticNode.Action = "Details";
staticNode.RouteValues.Add("id", person.Id.ToString());
yield return staticNode;
}
}
}
}
然后您的属性定义将如下所示:
[MvcSiteMapNode(Title = "Placeholder Title (won't be seen)", Key = "Accidents", PreservedRouteParameters = "personId", DynamicNodeProvider = "MyNamespace.PeopleDetailsDynamicNodeProvider, MyAssembly")]
动态节点提供程序没有限制您生成的节点数必须与数据库中的记录数完全匹配 - 如果需要,您可以根据需要创建更多节点。
注意:您可能需要根据数据的实际组织方式调整键/父键映射。