I'm trying to create a _Layout that will be used by all my Views, but my Sidebar and Header will contain data driven by a model. I have tried creating the sidebar and header as PartialViews and call them inside the _Layout.cshtml. That is causing a side effect that, in all my Index views that are used to render a body in Layout I have to pass the same model into them.
Here is how my _Layout looks
<body>
<section class="body">
<div class="inner-wrapper">
@{
Html.RenderPartial("~/Views/Home/_LeftSidebar.cshtml");
}
<section class="content-body">
@{
Html.RenderPartial("~/Views/Home/_Header.cshtml");
}
<div class="row">
@RenderBody();
@{
Html.RenderPartial("~/Views/Home/_RightSidebar.cshtml");
}
</div>
</section>
</div>
</section>
And here is how my HomeController looks:
public async Task<IActionResult> Index()
{
return View();
}
public PartialViewResult Header()
{
return PartialView();
}
public async Task<PartialViewResult> LeftSidebar()
{
string department = "Departments";
var departments = await _unitOfWork.DepartmentRepository.GetAllAsync(department);
return PartialView(departments);
}
And this is my _SideBar looks
@foreach(var item in Model)
{
<li class="nav-parent">
<a>
<i class="@item?.Icon" aria-hidden="true"></i>
<span>@item?.Name</span>
</a>
</li>
}
The Error that I'm getting is
System.NullReferenceException: 'Object reference not set to an instance of an object.' Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get returned null.
If I'm not using the PartialViews correct, or I should not use Partial in this case, What should I use?