Use ViewComponent in ASP.NET Core Razor Pages

On the Visual Studio, create new ASP.NET Core Web Application project

Select Empty Template

Click Ok button to Finish




Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreRazorPagesWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseMvc();
        }
    }
}

Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers




Create new folder named ViewComponents. In this folder, create new class named CategoryViewComponent.cs as below:

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace LearnASPNETCoreRazorPagesWithRealApps.ViewComponents
{
    [ViewComponent(Name = "Category")]
    public class CategoryViewComponent : ViewComponent
    {
        public async Task<IViewComponentResult> InvokeAsync()
        {
            List<string> categories = new List<string>() {
                "category 1", "category 2", "category 3", "category 4", "category 5"
            };
            return View("Category", categories);
        }
    }
}

Create new folder named Pages. In Pages folder, create new folder named Components. In Components folder, create new folder named Category. In Category folder, create new razor page named Category.cshtml as below:

<h3>Categories List</h3>
<ol>
    @foreach (var category in Model)
    {
        <li>@category</li>
    }
</ol>

In ViewComponents folder, create new class named VendorViewComponent.cs as below:

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace LearnASPNETCoreRazorPagesWithRealApps.ViewComponents
{
    [ViewComponent(Name = "Vendor")]
    public class VendorViewComponent : ViewComponent
    {
        public async Task<IViewComponentResult> InvokeAsync()
        {
            List<string> vendors = new List<string>() {
                "Vendor 1", "Vendor 2", "Vendor 3", "Vendor 4", "Vendor 5"
            };
            return View("Vendor", vendors);
        }
    }
}

In Components folder, create new folder named Vendor. In Vendor folder, create new razor page named Vendor.cshtml as below:

<h3>Vendors List</h3>
<ol>
    @foreach (var vendor in Model)
    {
        <li>@vendor</li>
    }
</ol>




In Pages folder, create new folder named Shared. In Shared folder, create Razor Layout named _Layout.cshtml as below:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>

    <table cellpadding="2" cellspacing="2" border="1">
        <tr>
            <td colspan="2">
                <a asp-page="index">Home</a> |
                <a asp-page="aboutus">About Us</a> |
                <a asp-page="news">News</a>
            </td>
        </tr>
        <tr>
            <td valign="top">
                @await Component.InvokeAsync("Category")

                @await Component.InvokeAsync("Vendor")
            </td>
            <td valign="top">
                @RenderBody()
            </td>
        </tr>
        <tr>
            <td colspan="2">
                Copyright PMK Lab
            </td>
        </tr>
    </table>

</body>
</html>

In Pages folder, create new Razor Page named Index as below:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class IndexModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel
@{
    ViewData["Title"] = "Home";
    Layout = "~/Pages/Shared/_Layout.cshtml";
}

<h1>Home</h1>




In Pages folder, create new Razor Page named AboutUs as below:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class AboutUsModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.AboutUsModel
@{
    ViewData["Title"] = "About Us";
    Layout = "~/Pages/Shared/_Layout.cshtml";
}

<h1>About Us</h1>

In Pages folder, create new Razor Page named News as below:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class NewsModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.NewsModel
@{
    ViewData["Title"] = "News";
    Layout = "~/Pages/Shared/_Layout.cshtml";
}

<h1>News</h1>




Open Index Razor Page with following url: http://localhost:1115

Open AboutUs Razor Page with following url: http://localhost:1115/AboutUs

Open News Razor Page with following url: http://localhost:1115/News