0
votes

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. The sidebar menu is in _layout.cshtml file.

I Add a Razor Page Using Entity Framework as a Partial View

enter image description here

Employees Partial View Page Model Code

 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.

<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'.

I searched and tried some solutions, but none of them works. I'm not experienced in ASP.NET Core. 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?

1

1 Answers

0
votes

By default, partials are passed the same model as the parent.

Add <partial name="_Employees" model="Employees" /> (make sure your partial views start with an underscore in razer pages). Also, you should name collections with plurals, so use Employees for your list rather than Employee.

You can also use the @Html.Partial() method instead, and pass the model.