[英]How to use Razor Page Using Entity Framework as a partial view in _layout.cshtml file in ASP.NET Core Razor Pages project?
In an ASP.NET Core Razor Pages Project, I want to get employees name from database and show them as menu items in sidebar menu.在 ASP.NET Core Razor Pages 项目中,我想从数据库中获取员工姓名并将其显示为侧边栏菜单中的菜单项。 The sidebar menu is in _layout.cshtml file.侧边栏菜单位于 _layout.cshtml 文件中。
I Add a Razor Page Using Entity Framework as a Partial View我使用实体框架作为部分视图添加了一个 Razor 页面
Employees Partial View Page Model Code员工部分查看页面 Model 代码
public class EmployeesModel : PageModel
{
private readonly OneStopContext _context;
public EmployeesModel(OneStopContext context)
{
_context = context;
}
public IList<Employee> Employee { get;set; }
public async Task OnGetAsync()
{
Employee = await _context.Employees.ToListAsync();
}
}
Employees Partial View - View Codes员工部分视图 - 查看代码
@model OneStopAdmin.Pages.EmployeesModel
@foreach (var item in Model.Employee) {
@item.FirstName
}
Then I simply add this partial view in _layout.cshtml file to show the items in sidebar menu.然后我只需在 _layout.cshtml 文件中添加这个部分视图,以在侧边栏菜单中显示项目。
<partial name="Employees"/>
But I get below error但我得到以下错误
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'OneStopAdmin.Pages.IndexModel', but this ViewDataDictionary instance requires a model item of type 'OneStopAdmin.Pages.EmployeesModel'. InvalidOperationException:传递到 ViewDataDictionary 的 model 项的类型为“OneStopAdmin.Pages.IndexModel”,但此 ViewDataDictionary 实例需要“OneStopAdmin.Pages.EmployeesModel”类型的 model 项。
I searched and tried some solutions, but none of them works.我搜索并尝试了一些解决方案,但没有一个有效。 I'm not experienced in ASP.NET Core.我在 ASP.NET 内核方面没有经验。 So How can I get data with Entity framework and show them in _layout.cshtml file as a partial view in ASP.NET Core Razor Pages project?那么如何使用 Entity 框架获取数据并将它们显示在 _layout.cshtml 文件中作为 ASP.NET Core Razor Pages 项目中的部分视图?
By default, partials are passed the same model as the parent.默认情况下,部分传递与父级相同的 model 。
Add <partial name="_Employees" model="Employees" />
(make sure your partial views start with an underscore in razer pages).添加<partial name="_Employees" model="Employees" />
(确保您的局部视图在 razer 页面中以下划线开头)。 Also, you should name collections with plurals, so use Employees for your list rather than Employee.此外,您应该将 collections 命名为复数形式,因此您的列表中使用Employees 而不是Employee。
You can also use the @Html.Partial()
method instead, and pass the model.您也可以改用@Html.Partial()
方法,并传递 model。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.