Create ViewComponent in ASP.NET Core MVC 5

On the Visual Studio, select Create a new project from Get Started

Select ASP.NET Core Web Application




Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create 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;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

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

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Demo}/{action=Index}/{id?}");
            });
        }
    }
}

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 LearnASPNETCoreMVC5.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("Index", categories);
        }

    }
}




Create new folder named Views. In Views folder, create new folders with path Views\Shared\Components\Category. In Category folder, create new folder named Index.cshtml:

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

In Views folder, create new folder named Shared. In this folder, create Razor Layout named _MasterLayoutPage.cshtml as below:

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

    <table border="1" cellpadding="2" cellspacing="2" width="500">
        <tr>
            <td colspan="2">
                <a asp-controller="home" asp-action="index">Home</a> |
                <a asp-controller="aboutus" asp-action="index">About Us</a> |
                <a asp-controller="news" asp-action="index">News</a>
            </td>
        </tr>
        <tr>
            <td valign="top">
                @await Component.InvokeAsync("Category")
            </td>
            <td valign="top">
                @RenderBody()
            </td>
        </tr>
        <tr>
            <td colspan="2">Copyright PMK Lab</td>
        </tr>
    </table>

</body>
</html>

In Controllers folder, create new controllers as below:

Create new controller named HomeController.cs as below:

using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("home")]
    public class HomeController : Controller
    {
        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            return View();
        }
    }
}




Create new controller named AboutUsController.cs as below:

using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("aboutus")]
    public class AboutUsController : Controller
    {
        [Route("index")]
        public IActionResult Index()
        {
            return View();
        }

    }
}

Create new controller named NewsController.cs as below:

using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("news")]
    public class NewsController : Controller
    {
        [Route("index")]
        public IActionResult Index()
        {
            return View();
        }

    }
}

In Views folder, create new views as below:

In Views/Home folder, create new view named Index.cshtml as below:

@{
    Layout = "~/Views/Shared/_MasterLayoutPage.cshtml";
}

<h2>Home Page</h2>




In Views/AboutUs folder, create new view named Index.cshtml as below:

@{
    Layout = "~/Views/Shared/_MasterLayoutPage.cshtml";
}

<h2>About Us Page</h2>

In Views/News folder, create new view named Index.cshtml as below:

@{
    Layout = "~/Views/Shared/_MasterLayoutPage.cshtml";
}

<h2>News Page</h2>




Access Index action in Home controller with following url: http://localhost:49328

Output

Access Index action in AboutUs controller with following url: http://localhost:49328/AboutUs/Index

Output

Access Index action in News controller with following url: http://localhost:49328/News/Index

Output