Member-only story
Using ViewComponent in ASP.NET Core
3 min readJan 30, 2025
In ASP.NET Core, ViewComponent works similarly to Partial Views but is more powerful and testable.
It operates independently of Controllers and can be called directly.
It is mainly used for displaying dynamic data and creating reusable components.
1. Basic ViewComponent Example
In this example, we will create a Recent Blog Posts component.
1.1. Creating the ViewComponent Class
First, create a ViewComponents folder and add a new class to it:
Project Folder
->ViewComponents
--> LatestPostsViewComponent.cs
LatestPostsViewComponent.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyApp.ViewComponents
{
public class LatestPostsViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
// Normally, data is retrieved from a database
var posts = new List<string>
{
"Using ViewComponent in ASP.NET Core",
"Best Practices for Entity Framework Core",
"Modern Web Development with Blazor"
};
return…