Search code examples
c#asp.net-mvcasp.net-core.net-8.0

Why do @Html.Action @Html.RenderAction not work in MVC .Net 8 project ? How can I pass data to a partial view from chosen by me controller and action?


I am trying to render partial view with data from Card controller in the \_Layout.cshtml. The problem is only @Html.Partial works. I said to myself: "Okay, i will try to pass the necessary data with ViewBag or ViewDate or even with dynamic model", but this did not work too. It only renders the view but with no data in it. It even does not go to the controller func while debugging.

Sidebar.cshtml:

<a href="javascript:void(0)">&times;</a>
@if (ViewBag.Cards != null)
{
    @foreach (var card in ViewBag.Cards)
    {
        <a>@card.Number</a>
    }
}
else
{
    <p>No cards available.</p>
}

_Layout.cshtml:

@Html.Partial("SideBar")

CardContoller:

var user = await userManager.GetUserAsync(User);
var cards = await cardService.GetAllCardsAsync(user.Id);

cards = cards.Select(c => new CardViewModel
{
    Id = c.Id,
    Balance = c.Balance,
    Number = c.Number,
    Transactions = c.Transactions
});

ViewBag.Cards = cards;
return PartialView("Sidebar",cards);`

Solution

  • "@Html.Action" is for old .net framework. In .net8 (asp.net core) You could try using ViewComponent. Try following:

    1. create a class MyPagesViewComponent.cs
        public class MyPagesViewComponent: ViewComponent
        {
            public IViewComponentResult Invoke()
            {
                string model = "test passing value";  //of course you can pass your object 
    
                return View("childPage1",model);
            }
        }
    
    1. Create folders and "childPage1.cshtml" like following hierarchy
      enter image description here
      childPage1.cshtml
    @model string    //pass model type
    
    @Model      // display model value
    
    1. In _Layout.cshtml add following code to somewhere
    ...
      @await Component.InvokeAsync("MyPages")
    ...
    

    Result
    enter image description here