[英]ASP.NET MVC - C# - Define Key Value Pair for use in Razor View
I have an ASP.NET MVC app. 我有一个ASP.NET MVC应用程序。 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?
如果没有,哪种方法更好?
您需要将ViewBag [“ Links”]强制转换为字典,以便foreach知道要迭代的内容。
@foreach(var link in (IDictionary<string, string>)ViewBag["Links"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.