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?
@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:
ViewComponents
folder at the root of the projectpublic class CounterViewComponent: ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(MyModel model)
{
// magic here
return View(model);
}
}
@await Component.InvokeAsync("Counter", new { model = Model })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With