使用MvcSiteMap如何创建指向下一个和上一个节点的链接?

时间:2014-10-09 13:13:40

标签: asp.net mvcsitemapprovider

我想在MvcSiteMapProvider中实现类似以下HTML帮助器的内容:

Html.MvcSiteMap().Previous()
Html.MvcSiteMap().Next()

但是,我对他们的API很陌生,是否可以这样做,如果是,那该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以通过构建自定义HTML帮助程序来实现此目的。我已经在GitHub上answered this question并提供了working demo project,但我在这里复制以供参考。

在文档中上下移动的逻辑看起来像这样,其余的代码大部分都是模板化的模板化HTML帮助程序代码。

private static ISiteMapNode GetNextNode(ISiteMapNode startingNode, IDictionary<string, object> sourceMetadata)
{
    ISiteMapNode nextNode = null;
    if (startingNode.HasChildNodes)
    {
        // Get the first child node
        nextNode = startingNode.ChildNodes[0];
    }
    else if (startingNode.ParentNode != null)
    {
        // Get the next sibling node
        nextNode = startingNode.NextSibling;
        if (nextNode == null)
        {
            // If there are no more siblings, the next position
            // should be the parent's next sibling
            var parent = startingNode.ParentNode;
            if (parent != null)
            {
                nextNode = parent.NextSibling;
            }
        }
    }

    // If the node is not visible or accessible, run the operation recursively until a visible node is found
    if (nextNode != null && !(nextNode.IsVisible(sourceMetadata) || nextNode.IsAccessibleToUser()))
    {
        nextNode = GetNextNode(nextNode, sourceMetadata);
    }

    return nextNode;
}

private static ISiteMapNode GetPreviousNode(ISiteMapNode startingNode, IDictionary<string, object> sourceMetadata)
{
    ISiteMapNode previousNode = null;

    // Get the previous sibling
    var previousSibling = startingNode.PreviousSibling;
    if (previousSibling != null)
    {
        // If there are any children, go to the last descendant
        if (previousSibling.HasChildNodes)
        {
            previousNode = previousSibling.Descendants.Last();
        }
        else
        {
            // If there are no children, return the sibling.
            previousNode = previousSibling;
        }
    }
    else
    {
        // If there are no more siblings before this one, go to the parent node
        previousNode = startingNode.ParentNode;
    }

    // If the node is not visible or accessible, run the operation recursively until a visible node is found
    if (previousNode != null && !(previousNode.IsVisible(sourceMetadata) || previousNode.IsAccessibleToUser()))
    {
        previousNode = GetPreviousNode(previousNode, sourceMetadata);
    }

    return previousNode;
}