Display SiteMap Links On ASP.NET Page

Code snippet that load a sitemap data and its links and displays them on a Web page in ASP.NET.

Create a sitemap sml based file and save it with sitemap.config name. Here is an example.

 

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <siteMap>  
  3. <siteMapNode title="Home" controller="Home" action="Overview">  
  4. <siteMapNode title="Dashboard" nopResource="Admin.Dashboard" controller="Home" action="Index" ImageUrl="~/Administration/Content/images/ico-dashboard.png" />  
  5. <siteMapNode title="Catalog" nopResource="Admin.Catalog" PermissionNames="ManageCatalog" ImageUrl="~/Administration/Content/images/ico-catalog.png" >  
  6. <siteMapNode title="Categories" nopResource="Admin.Catalog.Categories">  
  7. <siteMapNode title="List" nopResource="Admin.Common.List" controller="Category" action="List"/>  
  8. <siteMapNode title="Tree view" nopResource="Admin.Common.Treeview" controller="Category" action="Tree"/>  
  9. </siteMapNode>  
  10. </siteMap>  
If you're new to sitemap, learn here how to create a site map in Visual Studio.
 
To bind above sitemap and display on a page, please follow the below code example. 
  1. @using System.Data;  
  2. @using System;  
  3. <div class="page-title">  
  4. <h2>"Sitemap"</h2>  
  5. </div>  
  6. @{  
  7. string fileName = System.Web.HttpContext.Current.Server.MapPath("~/sitemap.config");  
  8. DataSet ds = new DataSet();  
  9. ds.ReadXml(fileName);  
  10. <table>  
  11. <tr>  
  12. <td width="20%"></td>  
  13. <td style="border: 2px double #CCCCCC; padding-left: 50px;" width="30%">  
  14. @for(int i=1;i<ds.Tables[0].Rows.Count/2;i++)  
  15. {  
  16. if(ds.Tables[0].Rows[i]["action"].ToString()=="")  
  17. {  
  18. <h4>@ds.Tables[0].Rows[i]["title"].ToString()</h4>  
  19. }  
  20. else  
  21. {  
  22. string url = "../" + @ds.Tables[0].Rows[i]["controller"].ToString() + "/" + @ds.Tables[0].Rows[i]["action"].ToString();  
  23. <ul class="top-menu"><li><a href="@url" temp_href="@url">@ds.Tables[0].Rows[i]["title"].ToString()</a></li></ul>  
  24. }  
  25. }  
  26. </td>  
  27. <td style="border: 2px double #CCCCCC; padding-left: 50px;" width="30%">  
  28. @for (int i = ds.Tables[0].Rows.Count / 2; i < ds.Tables[0].Rows.Count; i++)  
  29. {  
  30. if(ds.Tables[0].Rows[i]["action"].ToString()=="")  
  31. {  
  32. <h4>@ds.Tables[0].Rows[i]["title"].ToString()</h4>  
  33. }  
  34. else  
  35. {  
  36. string url = "../" + @ds.Tables[0].Rows[i]["controller"].ToString() + "/" + @ds.Tables[0].Rows[i]["action"].ToString();  
  37. <ul class="top-menu"><li><a href="@url" temp_href="@url">@ds.Tables[0].Rows[i]["title"].ToString()</a></li></ul>  
  38. }  
  39. }  
  40. </td>  
  41. </tr>  
  42. </table>  
  43. }  
Run application and you'll see a page with sitemap links.