我有一个带有布局页面的asp.net核心项目:
_Layout.cshtml
哪个是默认的asp.net核心_Layout页面。不涉及任何模型。
在Areas
文件夹中,我有几个文件:
Vendor > Pages > _ViewStart.cshtml
Vendor > Pages > _Menu.cshtml
Vendor > Pages > Index.cshtml
这些文件如下所示:
_ViewStart
@{
Layout = "/Views/Shared/_Layout.cshtml";
}
@{ await Html.RenderPartialAsync("_Menu"); }
_Menu
@page
@model MyProject.Areas.Vendor.Pages.MenuModel
@{
foreach(var i in Model.MenuItems)
{
@Html.ActionLink(i.DisplayText,i.Url)
}
}
索引
@page
@model MyProject.Areas.Vendor.Pages.IndexModel
@{
}
<h1>Hello, world!</h1>
现在,我想访问Vendor
索引的Razor页面,但我希望它也首先呈现_Menu
选项,因此,将_ViewStart
与_Layout
一起使用,并且_Menu
-基本上,我访问的每个供应商页面都应首先呈现_Menu
。
但是当我访问索引时,出现此错误:
The model item passed into the ViewDataDictionary is of type 'MyProject.Areas.Vendor.Pages.IndexModel', but this ViewDataDictionary instance requires a model item of type 'MyProject.Areas.Vendor.Pages.MenuModel'
怎么可能?我没有将任何内容传递到Index
页面吗?当我尝试将null
指定为RenderPartialAsync()
的参数时,我在_Menu页面上得到了null reference exception
。
我怎样才能实现我所需要的?
它应该呈现_Layout> _ViewStart> _Menu> AnyOtherVendorPage
答案 0 :(得分:1)
这是一个工作示例,如下所示:
1。部分视图应该是剃刀视图而不是剃刀页面:
@model List<YourProject.Models.MenuItem>
@{
foreach (var i in Model)
{
@Html.ActionLink(i.DisplayText, i.Url)
}
}
2._ViewStart.cshtml:
@{
Layout = "/Views/Shared/_Layout.cshtml";
var model = new List<YourProject.Models.MenuItem>()
{
new YourProject.Models.MenuItem(){ DisplayText="aaa", Url="aaa" },
new YourProject.Models.MenuItem(){ DisplayText="bbb", Url="bbb" },
};
}
@{ await Html.RenderPartialAsync("_Menu", model); }