locked
How to call an action method from a viewComponent class in ASP.NET Core 3.1 - MVC? RRS feed

  • Question

  • 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

    Monday, October 19, 2020 7:00 AM

All replies

  • User1312693872 posted

    Hi,ehsan_kabiri_33

    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().

    If you want to get data from another action, I suggest you use TempData, following is a little demo:

    Component.cs:

    public async Task<IViewComponentResult> InvokeAsync()
            {
                var items = TempData["MyModel"];
                    return View("Default", items);
            }

    Controller:

    public IActionResult Index()
            {
                TempData["MyModel"] = db.MyModels.ToList();   //modify it according to your needs
                return View();
            }

    Best Regards,

    Jerry Cai

    Tuesday, October 20, 2020 5:20 AM