Como: Programaticamente enumerar nós de mapas do site

Você pode usar controles de navegação para adicionar navegação a site às suas páginas da Web com pouco ou nenhum código, mas você também pode trabalhar com navegação a site através de programação.Quando o seu aplicativo Web é executado, o ASP.NET cria um objeto SiteMap que reflete a estrutura do mapa do site.O objeto SiteMap, por sua vez, expõe uma coleção de objetos SiteMapNode que contêm propriedades para cada nó no mapa do site.

Controles de navegação, como o controle SiteMapPath trabalham com os objetos SiteMap e SiteMapNode para processar automaticamente os links apropriados.

Você pode usar os objetos SiteMap e SiteMapNode no seu próprio código para criar navegação personalizada.

Exemplo

O exemplo de código a seguir mostra como exibir os títulos de todos os nós filhos para a página atual, contanto que a página atual é listada no arquivo do mapa de site.Se a página atual não estiver listada no arquivo do mapa do site, a primeira linha de código que usa o objeto SiteMap causará uma exceção NullReferenceException.

<%@ Page language="VB" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script >

  Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

    Try

      Dim LabelText As String = ""

      ' Displays the title of the current node.
      Label_CurrentNode.Text = SiteMap.CurrentNode.Title

      ' Determines if the current node has child nodes.
      If (SiteMap.CurrentNode.HasChildNodes) Then
        For Each ChildNodesEnumerator As SiteMapNode In SiteMap.CurrentNode.ChildNodes
          ' Displays the title of each node.
          LabelText = LabelText & ChildNodesEnumerator.Title & "<br />"
        Next
      Else
        LabelText = LabelText & "No child nodes."
      End If

      Label_ChildNodes.Text = LabelText

    Catch ex As NullReferenceException
      Label_CurrentNode.Text = "The current file is not in the site map."
    Catch ex As Exception
      Label_CurrentNode.Text = "Generic exception: " & e.ToString()
    End Try

  End Sub ' Page_Load

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>Enumerating Child Site Map Nodes</title>
  </head>
  <body>
    <form id="Form1" method="post" >

      <h2>Current Node</h2>
      <asp:Label ID="Label_CurrentNode" Runat="Server"></asp:Label>

      <h2>Child Nodes</h2>
      <asp:Label ID="Label_ChildNodes" Runat="Server"></asp:Label>

      <h2>Verify Against Site Map</h2>
      <asp:SiteMapDataSource ID="SiteMapDataSource1" Runat="server" />
      <asp:TreeView ID="TreeView1" Runat="server" DataSourceID="SiteMapDataSource1">
      </asp:TreeView>

    </form>
  </body>
</html>
<%@ Page language="c#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script >

  private void Page_Load(object sender, System.EventArgs e)
  {
    try
    {
      string LabelText = "";

      // Displays the title of the current node.
      Label_CurrentNode.Text = SiteMap.CurrentNode.Title;

      // Determines if the current node has child nodes.
      if (SiteMap.CurrentNode.HasChildNodes)
      {
        foreach (SiteMapNode childNodesEnumerator in SiteMap.CurrentNode.ChildNodes)
        {
          // Displays the title of each node.
          LabelText = LabelText + childNodesEnumerator.Title + "<br />";
        }
      }

      Label_ChildNodes.Text = LabelText;
    }
    catch (System.NullReferenceException ex)
    {
      Label_CurrentNode.Text = "The current file is not in the site map.";
    }
    catch (Exception ex)
    {
      Label_CurrentNode.Text = "Generic exception: " + e.ToString();
    }
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>Enumerating Child Site Map Nodes</title>
  </head>
  <body>
    <form id="Form1" method="post" >

      <h2>Current Node</h2>
      <asp:Label id="Label_CurrentNode" runat="Server"></asp:Label>

      <h2>Child Nodes</h2>
      <asp:Label id="Label_ChildNodes" runat="Server"></asp:Label>

      <h2>Verify Against Site Map</h2>
      <asp:SiteMapDataSource id="SiteMapDataSource1"  />
      <asp:TreeView id="TreeView1"  dataSourceID="SiteMapDataSource1">
      </asp:TreeView>

    </form>
  </body>
</html>

Segurança

Você pode ocultar os links na sua estrutura de navegação de usuários em funções específicas de segurança.Para obter mais informações, consulte Cortes de segurança em mapas de site no ASP.NET.

Consulte também

Tarefas

Como: Modificar programaticamente Site Map Nodes in memória

Conceitos

Tornando navegação em sites do ASP.NET seguro

Proteção de acesso a dados

Outros recursos

Segurança de aplicativos ASP.NET em ambientes hospedados