user70192
user70192

Reputation: 14204

ASP.NET MVC - C# - Define Key Value Pair for use in Razor View

I have an ASP.NET MVC app. My app needs to display breadcrumbs representing the user's location in the app. In an effort to do this, I wanted to have something like the following in a master layout page:

@foreach(var link in ViewBag["Links"])
{
  <div>|</div>
  <a href="@link.url">@link.text</a>
}

Then, in each view, I'd have something like the following at the top:

@{
    Layout = "~/Views/Layouts/_Breadcrumbed.cshtml";
    ViewBag.Links = new Dictionary<string, string>()
    {
        { "Home", "/home" },
        { "Parent", "/parent" }
    };
}

When this code executes, I get the following error:

Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'

I do not understand why I'm getting that. Am I doing down the correct path for creating a breadcrumb? If not, what approach is better?

Upvotes: 1

Views: 2952

Answers (1)

n8wrl
n8wrl

Reputation: 19765

You need to cast ViewBag["Links"] to your dictionary so foreach knows what to iterate on.

@foreach(var link in (IDictionary<string, string>)ViewBag["Links"])

Upvotes: 4

Related Questions