View Components in asp.net core 2 | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

View Components:

The view component is a class that inherits from ViewComponent and exposes an InvokeAsync method whose signature matches the input data you might be passing from the view in Razor. Here’s a reasonable layout for the view component core code.

It is a partial view that has its own model, which it gets from a method called Invoke in a controller-like class. A View Component’s model is independent from the current view’s model.

View Component views are always placed in a folder called Components inside the Views folder. If you place the folder in the Views/Shared folder, the view can be used from any view. Each View Component has a subfolder in the Components folder with the same name as the View Component.

Example 1:

Step1 : Create a new Folder at root with name “ViewComponents”.

Step2: Create a new class with suffix “ViewComponent” (In this example “MessageViewComponent)

Step3. Add following code into MessageViewComponent

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using CustomAuth.Models;

using Microsoft.AspNetCore.Mvc;

namespace CustomAuth.ViewComponents


    public class MessageViewComponent : ViewComponent


        public IViewComponentResult Invoke( /* input data */ )


            List<Employee> obj = new List<Employee>


                new Employee { id=1, Fname = “Yogesh”, Lname=”Sharma”},

                new Employee { id=2, Fname = “Yogesh1″, Lname=”Sharma1”},

                new Employee { id=3, Fname = “Yogesh2″, Lname=”Sharma2”}


            //var data = await RetrieveSomeDataAsync(/* input data */);

            return View(“Default”, obj);




Step 4: Create new folders “Components/Message” in Views/Shared Folder.

Step 5: Add Default.cshtml into Message Folder and add following code

@model List
    For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

    @foreach(var item in Model)

@item.id @item.Fname @item.Lname

Step 6: Create new controller and its action method and pass following code

public class UseViewComponentController : Controller
        public IActionResult Index()
            return View();



View Component Data:

@await Component.InvokeAsync("Message")