Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PartialAsync doesn't call coresponding controller method?

I have a .NET Core 2.1 MVC application.

I have a Home controller that looks like this:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult CountView(MyModel model)
    {
        ...
        return PartialView(model);
    }
}

In the Index view I want to display a patial view called CountView.

But when I use the following method in the Index.cshtml:

@await Html.PartialAsync("CountView", Model)

the view is displayed as I wanted to but the method in the controller never gets called and thus the partial view doesn't get the data it needs that is intended to be fetched by the controller method.

Why is that so?

And how can I make it to work as desired?

like image 603
Szybki Avatar asked Mar 05 '23 02:03

Szybki


1 Answers

@await Html.PartialAsync("CountView", Model)

Renders a Partial View, it doesn't call any Controller for that. The correct way for doing this in ASP.NET Core is to create a View Component.

As for the implementation, here's a simple one modified from the official documentation previously linked:

  1. Create a ViewComponents folder at the root of the project
  2. Inside it, create a ``CounterViewComponent` class:
public class CounterViewComponent: ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(MyModel model)
    {
        // magic here
        return View(model);
    }
}
  1. Call it in your view:
@await Component.InvokeAsync("Counter", new { model = Model })
like image 117
Camilo Terevinto Avatar answered Mar 16 '23 04:03

Camilo Terevinto