User-158191824 posted
I need to bind a Model to my Layout.cshtml so this is what I have done and it is working truly :
My ViewComponent
Class is created in a folder named ViewComponents
in my main project:
public class ItemsTitleViewComponent : ViewComponent
{
private readonly IUnitOfWork _unitOfWork;
public ItemsTitleViewComponent(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public async Task<IViewComponentResult> InvokeAsync()
{
IEnumerable<ItemsGroup> items = await _unitOfWork.itemsRepository.GetAll(includeProperties: "category");
return View(itemsGroups);
}
}
The view related to my viewComponent is created in a folder as below:
Views>Shared>Components>ItemsTitle>Default.cshtml
and my Default.cshtml is something like :
@model IEnumerable<Project.Models.Items>
// Something to get from data base and show ..
And in my Layout page or any *.cshtml that I want to use that view component :
@await Component.InvokeAsync("ItemsTitle");
Everything seems good but I do not know if using unitofwork injection in viewComponent class is true or not ! So I desided to call my Index action method in itemscontroller in Admin area to omit unitofwork from viewComponent class.
So I need the view component class to be simplified to something like this but I can not manage it:
public class ItemsTitleViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
IEnumerable<Items> items = ?? resultOfAction("mycontroller","myActionMethod","new {Area = "Admin"});
return View(items);
}
}
I do not know if it is possible or not to take the results of an action method in a view-component class and pass it to the related View().
Thanks