Click here to Skip to main content
Click here to Skip to main content

Breadcrumbs in ASP.NET

By , 24 Sep 2003
 
Prize winner in Competition "ASP.NET Jul 2003"

Breadcrumbs without file name appended

Breadcrumbs without file name appended

Breadcrumbs with file name appended

Breadcrumbs with file name appended

Introduction

Many popular web sites have a navigational menu near the top of each page so that the user can easily trace his or her steps back through the site. The menu usually looks something like the following (note that these links are inactive):

Home > Products > eWidge

This type of navigation has been named "Breadcrumb" navigation because it is analogous to dropping a trail of breadcrumbs while hiking into the woods, so that you can find your way back out again.

In Version 2, I have converted the script into a custom control.

This article assumes that you have a working knowledge of ASP.NET. To use this control, you must have the ability and knowledge to compile a simple C# script.

Background

I have started to try to learn ASP.NET several times now, but I keep getting sidetracked by my day job. I tackled this little project so that I could continue to learn more about ASP.NET. Since I am just getting started, I would really appreciate feedback on my code: Am I doing anything glaringly wrong? How can I make the script better? Is this code snippet useful to you?

How the code works

Assume we have a web site with the following directory structure:

/
/subdir/
/subdir/subsubdir/

Creating a breadcrumb navigation menu is as simple as extracting the directory names from the path of the current page and substituting the corresponding "friendly" names. (By "friendly" I mean a more human-readable, user-friendly form, so instead of seeing the directory name subdir, you would see the friendly name Sub Directory.) So if we were viewing the page /subdir/subsubdir/Default.aspx, our menu would look like this:

Home > Sub Directory > Sub Sub Directory > Default.aspx

This assumes, we assigned Sub Directory to subdir and Sub Sub Directory to subsubdir. It also assumes that the user has chosen to display the file name at the end of the breadcrumb trail.

During the control's load event, which is handled by the Control_Load event handler, the hyperlinks to each section are generated by appending each directory name to the web site's root URL, in succession.

Finally, after the file's path is parsed and the breadcrumbs are created, the resulting HTML is sent to the browser during the Render method via the HtmlTextWriter object.

Assigning friendly names is addressed in the next section.

Using the code

You will need to modify the directory names and "friendly" names in the HybridDictionary object named labels, located in the BreadCrumbControl constructor. You will need to change them to match the directory structure of your web site.

labels.Add ("subdir", "Sub Directory");
labels.Add ("subsubdir", "Sub Sub Directory");

Whenever you add a new directory to your web site, you must add an entry for it and then recompile the control. If you do not, the page will contain an incomplete breadcrumb trail.

If you have multiple directories with the same name (e.g., images), you only need to make one entry for that directory name.

I elected not to use Visual Studio to create this first version of the control. To compile the code, you may use a command line similar to the following:

csc /out:BreadCrumbs.dll /target:library BreadCrumbs.cs

After successful compilation, place BreadCrumbs.dll in the \bin directory of the web site's root directory.

To use the code, place the following Register directive at the top of your ASP.NET page:

<%@ Register TagPrefix="Sagara" Namespace="Sagara.BreadCrumbs" 
                                            Assembly="BreadCrumbs" %>

To display the breadcrumb control, place a custom control tag in the body of the page where you want the breadcrumbs to appear:

<Sagara:BreadCrumbControl id="breadcrumb" runat="Server" />

You may want to modify one or more of the four public properties to customize the look of the control. These properties have the following functions:

Variable Function
bool ShowFileName If true, show file name and separator (e.g.: Home > Sub Directory > Default.aspx). If false, don't show file name or separator (e.g.: Home > Sub Directory). Default value is false.
string RootName Contains the "friendly" name of the web site's root directory. Default value is Home
string RootUrl Contains the URL of the web site's root directory. Default value is /.
string Separator The HTML character used to separate the "friendly" directory names in the breadcrumb HTML. Default value is >.

For example, to change the separator character to :, you would change the control's tag to the following:

<Sagara:BreadCrumbControl id="breadcrumb" Separator=":" runat="Server" />

Alternatively, you may modify these properties in the code-behind file prior to compilation.

To-do list

  • Per user suggestion, I am investigating the possibility of incorporating data binding into this control.

Conclusion

That's it! As you can see, breadcrumb navigation is very simple in concept and implementation.

If you have any questions, please leave them on the message boards below, and I will respond as soon as possible!

History

  • 1.0.0 - 23 Aug 2003

    Initial public release.

  • 2.0.0 - 23 Sep 2003

    Converted script into a custom control.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jon Sagara
Software Developer (Senior) Sagara Software, Inc.
United States United States
Member
Jon graduated from Cal Poly with a B.S. Computer Engineering. He is currently building a Silverlight-based report scheduling interface for a pharmaceutical reporting company.
 
When he's not fooling around with computers or reading, he's busy spending time with his super wife, Kelly, his two boys, and their rambunctious dog, Homer.
 
Visit my blog
 
---
 
View my old profile pictures

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionMy vote of 5 !!memberSanjay_00722 Dec '11 - 1:28 
Great article !! Thank you very much !
GeneralNot workingmemberNagarjuna M20 Apr '11 - 2:27 
Hi
I am doing dynamic binding using this Menu control, Please help me for sample code for dynamic breadcrumb when i am selecting a particular link in Menu control..
 
Thanks in advance.
 

 

 
Regards,
Nag
GeneralMy vote of 5membermohanudupa14 Feb '11 - 16:55 
It helped me a lot to create a breadcrumb of ma own..
QuestionWhere is the User Control File?memberSatish Penta31 May '10 - 20:26 
User Control Source File is missing.
Satish

GeneralFile or assembly name BreadCrumbs, or one of its dependencies, was not foundmemberLori Tompkins6 May '05 - 13:00 
I am not doing something correctly with the placement of the bin or dll file.
For now, this project is in inetpub and I used Visual studio 2003 to compile the project.
To keep it simple, I created a VS project called Sagat/BreadCrumbs
It's in Sagat/BreadCrumbs I compiled the code.
 
Then I have a content folder. Within content I have the two subdirectories.
I have tried keeping the Sagat/Breadcrumbs project top-level within inetpub/wwwroot, as well
 
as placing it in the content folder.
 
I am getting this error no matter what I do. Any suggestions would be appreciated.
 
Line 1: <%@ Page Language="C#" %>
Line 2: <%@ Register TagPrefix="Sagara" Namespace="Sagara.BreadCrumbs"
 
Assembly="BreadCrumbs" %>
Line 3: <html>
Line 4: <head>

 
Source File: C:\Inetpub\wwwroot\lori\Lori1.aspx Line: 2
 
Assembly Load Trace: The following information can be helpful to determine why the assembly
 
'BreadCrumbs' could not be loaded.
 

=== Pre-bind state information ===
LOG: DisplayName = BreadCrumbs
(Partial)
LOG: Appbase = file:///C:/Inetpub/wwwroot
LOG: Initial PrivatePath = bin
Calling assembly : (Unknown).
===
 
LOG: Policy not being applied to reference at this time (private, custom, partial, or
 
location-based assembly bind).
LOG: Post-policy reference: BreadCrumbs

GeneralRe: File or assembly name BreadCrumbs, or one of its dependencies, was not foundmemberJon Sagara6 May '05 - 13:34 
I wrote this control outside of Visual Studio so that people who don't have VS could still easily use it. If you want a quick fix, edit the source file directly and then use the command line instruction in the file's comment header to compile with csc.exe. Drop the resulting file into the \bin directory. To be completely honest with you, I have never tried using this from within VS.
 
What is the assembly name of your new project that you created? Given the ASP.NET Page and Register directives above, it is looking for an assembly named "BreadCrumbs.dll" in the \bin directory. If you modified the namespace(s) or the assembly name, you'll need to modify the Register directive at the top of Lori1.aspx to reflect the new names.
 

Jon Sagara
I said NO salt, NO salt on my margarita!!

My Articles

GeneralCan't change font sizesussAnonymous7 Feb '05 - 2:04 
Despite setting the properties in the IDE and in code, the font size always remains the same.
GeneralRe: Can't change font sizememberJon Sagara7 Feb '05 - 4:34 
This control wasn't designed to be dropped into the IDE and used from the designer (I built it when I was first learning ASP.NET Blush | :O ). If you want to set the font size, you'll have to either manually edit the code or use a stylesheet.
 
You bring up a good point -- it needs to work in the designer. Thanks for the input.
 

Jon Sagara
I bent my wookie.

My Articles

GeneralCan't display static text at end w/o it wrappingmemberjopagri649 Feb '04 - 6:09 
Here's my code:
 
<BreadCrumb:BreadCrumbControl id="Internet" runat="Server" /> > Current Page Title Here
 
I get:
Home > SubDir //note line break
"> Current Page Title Here"
 
I want:
Home > SubDir "> Current Page Title Here"
 
What am I doing wrong? I've tried wrapping it all in a <nobr> tag.
GeneralRe: Can't display static text at end w/o it wrappingmemberJon Sagara9 Feb '04 - 9:28 
jopagri64 wrote:
> Current Page Title Here
 
Just a guess, but try replacing that > with &gt;. Failing that, I'll need to see the HTML that makes up your page.
 

Jon Sagara
Vegetarianism is unhealthy. Humans need protein, and lots of it. Put down those sprouts and pick up a T-bone!
-- Michael Moore


Latest Article: Breadcrumbs in ASP.NET

GeneralRe: Can't display static text at end w/o it wrappingmemberjopagri649 Feb '04 - 10:10 
here's the bare bones version...
 
<%@ Register TagPrefix="BreadCrumb" Namespace="Internet" Assembly="Internet" %>
<html>
<body>
<BreadCrumb:BreadCrumbControl id="Internet" runat="Server" /> &#187; Current Page Title Here
</body>
</html>
 
I experience the same line-break problem.
GeneralRe: Can't display static text at end w/o it wrappingmemberjopagri649 Feb '04 - 10:15 
Nevermind found the cause...The BR tag in the output string.
 
     protected override void Render (HtmlTextWriter output)
          {
               output.Write (sbResult.ToString () + "<br>");
          }
QuestionWithout the ascx?sussDaniel Plomp4 Feb '04 - 22:43 
Is it also possible to use the class without compiling it?
I have converted the class to VB.NET, because my app is written in it. I just want to use the class in my project.
 
How can I do this? I hope someone can give me some advice.
 
Thanks
AnswerRe: Without the ascx?memberJon Sagara5 Feb '04 - 19:12 
You can take the code out of the .cs page and make it a server side include, or you can make a user control out of it.
 

Jon Sagara
Vegetarianism is unhealthy. Humans need protein, and lots of it. Put down those sprouts and pick up a T-bone!
-- Michael Moore


Latest Article: Breadcrumbs in ASP.NET

Generalone way for breadcrumbs...membervbaddict2 Oct '03 - 5:13 
Actually, this is one way to do breadcrumbs, and by far the easiest way; however, if you follow the analogy of breadcrumbs then the trail should be the pages that you have actually been on rather than a trail of directory/subdirectories.
 
So the way that would work is the person clicks on Page1, while there he sees a cool link to another area of the site and clicks that (Page 2), then goes to an entirely different area of the site (Page 3). The "breadcrumb" trail should look something like this: (Page1 / Page2 / Page3). That way, when the person ends up on Page3 and he wanted to get to the very first page that he hit, he clicks Page1. I think one way of achieving this would be to create a collection object that has page/url pairs that could be part of the users' session...anybody else have any thoughts on this?
 
John Beutler
Merant
www.merant.com
GeneralRe: one way for breadcrumbs...memberJon Sagara2 Oct '03 - 9:42 
That's what the Back button does. Wink | ;)
 
I think it is more useful to the user to have a breadcrumb trail based on the site's structure rather than an audit trail of pages they have visited. It lets them know where they are and provides hints on where they need to go to access other content. But that is just my humble opinion.
 
I must admit that I have never seen an implementation like you suggest. Can you provide an example Web site?
 


Jon Sagara

A bottle a night isn't alcoholism - it's persistence!
-- A coworker, jokingly



Latest Article: Breadcrumbs in ASP.NET



GeneralRe: one way for breadcrumbs...membervbaddict3 Oct '03 - 6:21 
Here's a good link on the topic of "Breadcrumb Navigation". The author details 3 types of breadcrumb navigation: Path, Location, and Attribute. I was refering to a "Path" breadcrumb scheme, which quite honestly has some pitfalls and even the author of the article poses the question regarding who is responsible for path...the site or browser? In any case, it may add some depth to different breadcrumb implementations.
 
http://user-experience.org/uefiles/breadcrumbs/KEI-Breadcrumbs-IAS.pdf
 
John Beutler
www.merant.com
GeneralRe: one way for breadcrumbs...memberMichael Dausmann9 Nov '03 - 3:12 
This is an interesting article. I am interested in 'path' based breadcrumbs, less as a navigational aid for the user, more as a means for me as the page developer to keep track of where the user came from so as i can get them back there without any hassle. eg if the user has come from a static (html) page, requested a secure aspx page, been redirected to login, chosen to 'create new account', then I need to get them back to where they started Unsure | :~
 
whatever I do though I will be using a control for encapsulation of the code, neat idea and clean example. Thanks a bunch Smile | :)
 
Michael Dausmann
www.poweredbyusers.com
GeneralRe: one way for breadcrumbs...groupBabuRao Gummadela31 Aug '09 - 21:20 
hey its good and nice presentation man,
hey i need the code for that what u did earlier i am unable to run successfully the code of sagara .
so any help is apprciatable.
plz be quick if u have.
hope u will send
bye bye
GeneralRe: one way for breadcrumbs...sussAnonymous6 Jan '04 - 4:00 
Jon, my needs are very specific.
 
I have a couple of hundred products, each connected with several markets and industries. The products have a 1:1 relationship with a product page, but the industries and markets are open-endedly hierarchical. All of this is kept in a database.
 
Users can browse through any number of ways... markets, industries, products. The hierarchical nature of things is designed by the marketing department, and the browsing of it is left up to the user.
 
(1) The entire system is dynamic. Hierarchical relationships can go as deep as the marketing folk desire. How do I represent this in the UI? Certainly not using any type of menu system. Breadcrumbs work very well. Since this is dynamic, forget any style of XML, forget any clunkiness of setting up a physical hierarchy either. When drilling down into a particular industry, I want the user to grasp the concept of looking at a 'thread'... and breadcrumbs are the ideal way of navigating.
 
(2) Yes, the Back button works quite well. But the Back button relays no info to the user - at least I'm not aware of a DOM that allows me to alter the button text! Smile | :) How does the user know where in this hierarchy they are? Again, breadcrumbs. Based not on some physical piece of info, but on how they navigated to the page they are seeing.
 
Can't yet provide you with an example, our site is only in final test mode. Next week maybe! But I hope this provides a scenario where visited pages are the proper solution.
 
Dave
GeneralRe: one way for breadcrumbs...susskimjc015 Mar '04 - 10:29 
Hi Jon,
 
Good work on your breadcrumbs control. One comment, the Back button does weird things unless you turn SmartNavigation on. Turning SmartNavigation on does weird things to your code, if you're not careful. This can of worms continues without end...
 
In the meantime, I think that you can implement the breadcrumb to support the Path method, with the following logic changes:
1) First, each page which you want supporting breadcrumbs will need to have the control on the page (hope I don't come off as too stoopid here for stating the obvious...)
2) Each time you load a new page, on that page's PageLoad event, add the page to a Stack object. Set the stack (or perhaps a collection?) object into a Session variable. I suggest that you name the session var into something quite unique, perhaps also blending it with the homesite name, etc.
3) When the user clicks on a path on the breadcrumb, fetch the stack from the session, pop (unload) the stack until you get to the level he clicked on, and navigate the page to the path stored in the stack. Update the session variable again.
4) Update the breadcrumb visually so that it only reflects the current path structure. Since you have popped the stack items already, the stack in the session should be synchronized to the breadcrumb.
 
I have already implemented this technique already with good results, only not with a breadcrumb control, but instead as a base web page that I descend all my other web pages from.
 

Once agin, thanks for the article, it's given me more food for thought.
Smile | :)
GeneralRequest objectmembergleizerowicz2 Oct '03 - 2:59 
Quick suggestion - use the Page.Request.Url object to get the scheme, server, and current path. At the very least, you can dynamically determine the scheme so your control will work over http and https.
GeneralRe: Request objectmemberJon Sagara2 Oct '03 - 9:42 
Thanks for the great suggestion. Smile | :)
 


Jon Sagara

A bottle a night isn't alcoholism - it's persistence!
-- A coworker, jokingly



Latest Article: Breadcrumbs in ASP.NET



GeneralNot working with UrlRewritingmemberLennybacon30 Sep '03 - 8:46 
the only bad thing about it.
 
# THIS CODE AND INFORMATION ARE PROVIDED
# "AS IS" WITHOUT WARRANTY OF ANY
# KIND, EITHER EXPRESSED OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE
# IMPLIED WARRANTIES OF MERCHANTABILITY
# AND/OR FITNESS FOR A PARTICULAR PURPOSE.
# http://www.lennybacon.com/
GeneralRe: Not working with UrlRewritingmemberJon Sagara30 Sep '03 - 8:52 
How are you doing your URL Rewriting? As explained here on CodeProject? (URL Rewriting[^])
 


Jon Sagara

A bottle a night isn't alcoholism - it's persistence!
-- A coworker, jokingly



Latest Article: Breadcrumbs in ASP.NET



General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 25 Sep 2003
Article Copyright 2003 by Jon Sagara
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid