Csharp 12
Csharp 12
Csharp 12
Since, we want to display the Employee Head Count Summary on several pages, it
makes sense to create a reusable component.
What we do not want to do is include the code on each page. This approach
duplicates code.
We can't use a partial view either, because a partial view cannot have it's own
data access logic. It depends on the data passed from the parent view or razor
page. We do not want to include the code that retrieves data on each page. This is
again code duplication. We want something that can retrieve data independently and
render. View Component is a perfect choice for this.
Create View Components folder, in the root project directory. We will place all our
view components in this folder. Add a new class file with name -
HeadCountViewComponent.cs. Copy and paste the following code.
using Microsoft.AspNetCore.Mvc;
using RazorPagesTutorial.Services;
namespace RazorPagesTutorial.ViewComponents
{
public class HeadCountViewComponent : ViewComponent
{
private readonly IEmployeeRepository employeeRepository;
@model IEnumerable<DeptHeadCount>
@await Component.InvokeAsync("HeadCount")
Supporting classes
namespace RazorPagesTutorial.Services
{
public interface IEmployeeRepository
{
// Other methods
IEnumerable<DeptHeadCount> EmployeeCountByDept();
}
}
namespace RazorPagesTutorial.Services
{
public class MockEmployeeRepository : IEmployeeRepository
{
private List<Employee> _employeeList;
public MockEmployeeRepository()
{
_employeeList = new List<Employee>()
{
new Employee() { Id = 1, Name = "Mary", Department = Dept.HR,
Email = "mary@pragimtech.com", PhotoPath="mary.png" },
new Employee() { Id = 2, Name = "John", Department = Dept.IT,
Email = "john@pragimtech.com", PhotoPath="john.png" },
new Employee() { Id = 3, Name = "Sara", Department = Dept.IT,
Email = "sara@pragimtech.com", PhotoPath="sara.png" },
new Employee() { Id = 4, Name = "David", Department = Dept.Payroll,
Email = "david@pragimtech.com" },
};
}