Click here to Skip to main content
6,597,576 members and growing! (21,689 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

Localized Breadcrumbs in ASP.NET with UrlRewriting support

By Daniel Fisher (lennybacon)

This article describes how to create localized breadcrumb navigation with ASP.NET, based on its directory structure with UrlRewriting support.
C#.NET 1.1, Win2K, WinXP, Win2003, ASP.NET, VS.NET2003, Dev
Posted:1 Oct 2003
Updated:24 Jul 2005
Views:66,118
Bookmarked:58 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
10 votes for this article.
Popularity: 4.14 Rating: 4.14 out of 5
3 votes, 30.0%
1

2

3
2 votes, 20.0%
4
5 votes, 50.0%
5

Introduction

After I read Jon Sagara's excellent article Breadcrumbs in ASP.NET I tried to include Breadcrumbs in my web site.
But there were two problems:

  1. My Website uses UrlRewriting
  2. My Website is localized to the the User's Browser.AcceptedLanguage[0]

So I decided to write my own Breadcrumb-Control.

Background

This is my first article on CodeProject. I hope Jon Sagara isn't angry about me that i took his and mine ideas together and show what the results are, because he did the main job and gave me the inspiration for this.

What is a breadcrumb navigation

A typical web site has a directory structure. e.g.:

/
/Products
/...

A breadcrumb navigation now takes the path of the current page (e.g. http://companyname/products/default.apsx) and converts it to:

/ CompanyName / Products / Overview 

or

/ Products / Default

The Control code

if(HttpContext.Current.Application["HTTP_HOST"]==null)
{
    HttpContext.Current.Application["HTTP_HOST"] = 
           HttpContext.Current.Request.Headers["HOST"];
}
string hostName = HttpContext.Current.Application["HTTP_HOST"];
bool capitalize = false;

string requestBasePath = HttpContext.Current.Request.Path;
string requestPath = requestBasePath;
int queryStringCount = 0;
foreach ( string key in HttpContext.Current.Request.QueryString )
{
    if(queryStringCount==0)
    {
        requestPath += "?";
    }
    else
    {
        requestPath += "&";
    }
    requestPath += key + "=" + HttpContext.Current.Request.QueryString[key];
}
Assembly assmebly = Assembly.GetExecutingAssembly();
string configFile = 
   System.Web.HttpContext.Current.Request.PhysicalApplicationPath + 
   "bin\\" + assmebly.GetName().ToString().Split(',')[0] + ".config";

object breadCrumb = 
  StaticDust.Configuration.ConfigurationSettings.AppSettings(
  configFile)[System.Globalization.CultureInfo.CurrentCulture +
  "@" + requestPath];
if(breadCrumb==null)
{
    breadCrumb = StaticDust.Configuration.ConfigurationSettings.AppSettings(
        configFile)[System.Globalization.CultureInfo.CurrentCulture  + 
    "@" + requestBasePath];
    if(breadCrumb==null)
    {
        breadCrumb = 
             StaticDust.Configuration.ConfigurationSettings.AppSettings(
             configFile)[this.m_DefaultCulture + 
        "@" + requestPath];
        if(breadCrumb==null)
        {
            breadCrumb = 
                StaticDust.Configuration.ConfigurationSettings.AppSettings(
                configFile)[this.m_DefaultCulture + 
            "@" + requestBasePath];
            if(breadCrumb==null)
            {
                breadCrumb = requestBasePath;
                capitalize = true;
            }
        }
    }
}

string[] breadcrumbArr = breadCrumb.ToString().Split('/');
string outputString = "";
string urlpath = "";
for(int i=0; i<breadcrumbArr.Length; i++)
{
    if(breadcrumbArr.Length==1)
    {
        urlpath = "/" + breadcrumbArr[i];

    }
    else
    {
        if(i==0)
        {
            urlpath = "/" + m_DefaultDoc;
        }
        else if(i==(breadcrumbArr.Length-1))
        {
            urlpath += requestPath.Substring((requestPath.LastIndexOf("/")),
                 (requestPath.Length-requestPath.LastIndexOf("/")));
            if(this.m_HideFileExt==true)
            {
                breadcrumbArr[i] = breadcrumbArr[i].Substring(0, 
                   breadcrumbArr[i].LastIndexOf("."));
            }
        }
        else
        {
            urlpath += "/" + breadcrumbArr[i] + "/" + m_DefaultDoc;
        }
    }

    if(i==(breadcrumbArr.Length-1) && this.m_LinkFiles==false)
    {
        outputString += ((capitalize == true && breadcrumbArr[i].Length>=2) 
              ? (breadcrumbArr[i].Substring(0,1).ToUpper() +
              breadcrumbArr[i].Substring(1,
              (breadcrumbArr[i].Length-1)).ToLower()) : breadcrumbArr[i] ) +
              this.m_Seperator;
    }
    else
    {
        outputString += "<a href=\"" + urlpath + "\">" +
             ((capitalize == true && breadcrumbArr[i].Length>=2) ? 
             (breadcrumbArr[i].Substring(0,1).ToUpper() +
             breadcrumbArr[i].Substring(1,
             (breadcrumbArr[i].Length-1)).ToLower()) : breadcrumbArr[i] ) +
             "</a>" + this.m_Seperator;
    }
    urlpath = urlpath.Replace("/" + m_DefaultDoc,"");

}

outputString = outputString.Substring(0,
    (outputString.Length-this.m_Seperator.Length));
output.Write(outputString);
}

To get the path translated to a breadcrumb the control first checks it's configuration file (I used a custom library for that and show details of that in my next article) for an entry looking like this one:

<configuration>
  <appSettings>
    <add key="en-US@/products/default.aspx" value="CompanyName/Products" />
  </appSettings>
</configuration>

The key contains the localized culture (so you can add different values for different languages), an @ as separator and the request path. You can also define a DefaultCulture that can be used if the users culture has net been defined (default is en_US).

To support UrlRewriting via HttpContext.Current.RewritePath(...) you can also add entries looking like this:

<configuration>
  <appSettings>
    <add key=en-US@/default.aspx?content=products 
          value="CompanyName/Products" />
  </appSettings>
</configuration>

If the retrieved value is null the control looks for the same requested path but without the query string, so a correct bread crumb is shown when you work with query strings.

If you haven't defined anything in the configuration file the directory names and the file name will be capitalized and by default the extension is removed (/products/default.aspx gets /Products/Default).

If you are not using Visual Studio .NET you can compile the code with following command line:

csc.exe /out:StaticDust.Web.UI.Controls.BreadCrumbs.dll /target:library 
    BreadCrumbs.cs AssemblyInfo.cs /r:StaticDust.Configuration.dll

The ASP.NET code

To use the control in an .asxp page add following line to the head:

<%@ Register TagPrefix="ctrl" Namespace="StaticDust.Web.UI.Controls" 
    Assembly="StaticDust.Web.UI.Controls.BreadCrumbs" %>

And place the control tag where you want the breadcrumbs to be shown:

<ctrl:BreadCrumbs runat="server" />

History

  • 10/03/2003 v.1.0.0.0.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Daniel Fisher (lennybacon)


Member
Daniel Fisher is co-founder of devcoach. He supports since 1997 customers and projects in Germany and throughout Europe. As a consultant and developer he has worked several years on projects for insurance companies, distributors, mobile communications hardware, construction supplies and various other companies of different branches. He has a strong emphasis on service-orientation, agile methods, the web and data access. He is a frequent speaker on national and international software developer conferences in Germany, England and Poland. Daniel is actively contributing the software developer community as lead of a user group and organizer of the biggest regional software developer community event. You can read his blog by visiting lennybacon.com.
Occupation: Web Developer
Location: Germany Germany

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 10 of 10 (Total in Forum: 10) (Refresh)FirstPrevNext
Generalhelp Pinmembersreejith ss nair22:15 18 Sep '05  
GeneralRe: help Pinmembersreejith ss nair18:38 22 Sep '05  
GeneralDocumentation Pinmemberbernardoh8:15 21 Jul '05  
GeneralRe: Documentation PinmemberDaniel Fisher (lennybacon)3:19 22 Jul '05  
GeneralRe: Documentation Pinmemberbernardoh4:33 22 Jul '05  
GeneralRe: Documentation PinmemberDaniel Fisher (lennybacon)3:44 24 Jul '05  
GeneralYour code has a flaw in it. PinmemberRedMediaGab10:25 19 Aug '04  
GeneralRe: Your code has a flaw in it. PinmemberDaniel Fisher (lennybacon)3:21 22 Jul '05  
GeneralScreenshot PineditorHeath Stewart4:07 3 Oct '03  
GeneralRe: Screenshot PinmemberLennybacon4:54 3 Oct '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Jul 2005
Editor: Smitha Vijayan
Copyright 2003 by Daniel Fisher (lennybacon)
Everything else Copyright © CodeProject, 1999-2009
Web12 | Advertise on the Code Project