2

I have a controller, which creates breadcrumbs as follows:

Software > Windows 7 > Outlook 2007

The code to create this is:

ViewBag.breadcrumbs = string.Join(" > ", cbh.Select(i => i.Title));

Is there a straightforward way of making the breadcrumbs hyperlinks, which would point to (i.ParentID) ie:

Software -> forum/index/12
Windows 7 -> forum/index/19
Outlook 2007 -> forum/index/23

Or should I just loop through cbh and manually build <a href=...> strings, and pass those to the view?

Thank you,

Mark

2 Answers 2

3

Your best bet is to put the required items into the model then loop through them.

Try something like this:

Model

public class Model
{
    public struct BreadCrumb
    {
        public string Title;
        public string Url;
    }

    public List<BreadCrumb> Breadcrumbs { get; set; }
}

View

@{ int index = 0; }
@foreach(var crumb in this.Model.Breadcrumbs)
{
    <a href="@(crumb.Url)" title="@(crumb.Title)">@(crumb.Title)</a>

    if(index < this.Model.Breadcrumbs.Count - 1)
    {
        <span>&gt;</span>
    }

    index++;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, you should build your breadcrumb links in the view. If it helps, you can create a BreadCrumbModel class (if you don't already have one).

ViewBag.breadcrumbs = cbh.Select(i => new BreadCrumbModel() 
                                      {
                                          Id = i.Id, 
                                          Title = i.Title 
                                      });

@{ 
    var printSeparator = false;
}
@foreach(BreadCrumbModel bc in ViewBag.breadcrumbs)
{
    @if(printSeparator)
    {
        <span class="breadcrumb-separator">&nbsp;&gt;&nbsp;</span>
    }
    <span class="breadcrumb">
      @Html.ActionLink(bc.Title, "index", "forum", new { id = bc.Id });
    </span>
    @{
        printSeparator = true;
    }
}

If you want to have breadcrumbs between different controllers and actions (not just forum / index), then add those as properties of your BreadCrumbModel.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.