View Components in ASP.NET Core MVC

View Components in ASP.NET Core MVC

In this article, I am going to discuss View Components in ASP.NET Core MVC Application with Examples. Please read our previous article discussing Different Ways to Render Partial Views in ASP.NET Core MVC Applications. At the end of this article, you will understand the following pointers.

  1. What are the View Components in ASP.NET Core MVC?
  2. What Are All Files Available in a View Component in ASP.NET Core MVC?
  3. What Should be the Location for the Files of View Components in ASP.NET Core?
  4. How to invoke a View Component from a View File in ASP.NET Core MVC?
  5. Example to Understand View Component in ASP.NET Core MVC.
  6. How Does View Component Work in ASP.NET Core MVC?
  7. When Should We Use View Component in ASP.NET Core MVC?
  8. View Component vs. Partial View in ASP.NET Core MVC
What are the View Components in ASP.NET Core MVC?

View Components in ASP.NET Core MVC are reusable components designed to encapsulate rendering logic that can be invoked from multiple places. They are similar to partial views, but they can have their own logic, making them suitable for creating dynamic content that requires processing. View Components are ideal for situations where you need to display information that requires some business logic to fetch or generate the displayed data.

What Are All Files Available in a View Component in ASP.NET Core MVC?

A view component typically consists of 2 files in ASP.NET Core MVC. They are as follows:

  • Server-Side File (.cs file).
  • Client Side File (.cshtml file)
What Should be the Location for the Files of View Components in ASP.NET Core?

In ASP.NET Core, there is a special place for the view component’s file.

Server-side file (.cs): This file can be created anywhere in the project. But we generally create a new folder (with the name Components, ViewComponents, or any other name as per your choice) at the root level of the project and put all the view components in this new folder.

Client-side file (.cshtml): The client-side file of a view component must be placed at a specific location.

  • Location 1: If we want to call the view component from the controller’s action method, then we need to add the view component client-side file at the following location- /Views/{Controller Name}/Components/{View Component Name}/{View Name}
  • Location 2: If we want to call the view component from the other cshtml file, then we need to add the view component client-side file at the following location- /Views/Shared/Components/{View Component Name}/{View Name}
  • Location 3: If we are using a view component in Razor pages, then we need to add the view component client-side file at the following location- /Pages/Shared/Components/{View Component Name}/{View Name}

Note: The name for each view component file should be Default.cshtml. But you can also have other names for your view component client-side file. But the recommended one is Default.cshtml

How to invoke a View Component from a View File in ASP.NET Core MVC?

To use a view component, you can invoke it from a view using the Component.InvokeAsync HTML Helper method, passing the name of the component and any necessary parameters. View components do not use model binding, so you need to pass any required data explicitly. We can invoke the view component from a view file by using the following syntax:

@await Component.InvokeAsync(“Name of view component”, {Anonymous Type Containing Parameters});

How to invoke a View Component from a View File using Tag helper ASP.NET Core MVC?

View components can also be invoked using Tag Helper on any view (cshtml) file using the following syntax.

<vc:[view-component-name]
      parameter1=”parameter1 value”
      parameter2=”parameter2 value”>
</vc:[view-component-name]>

Example to Understand View Component in ASP.NET Core MVC Web Application

We want to display top products on the web page using the View Component. Let us see the step-by-step process to implement this using the View Component. First, create a new ASP.NET Core Web Application using the Model-View-Controller Project template with the name ViewComponentInMVC.

Product Model:

Create a class file named Product.cs within the Models folder, and then copy and paste the following code. This is going to be our model, which will hold the product information.

namespace ViewComponentInMVC.Models
{
    public class Product
    {
        public long ProductID { get; set; }
        public string? Name { get; set; } = null!;
        public string Category { get; set; } = null!;
        public string Description { get; set; } = null!;
        public decimal Price { get; set; }
    }
}
ProductRepository File:

Create a Class file named ProductRepository.cs within the Models folder, and then copy and paste the following code. The code for getting the top products from the database is written in the ProductRepository.cs file. You will get the data from the database in real time, but here, we have hard-coded it.

namespace ViewComponentInMVC.Models
{
    public class ProductRepository
    {
        public async Task<List<Product>> GetTopProductsAsync(int count)
        {
            IEnumerable<Product> products = new List<Product>()
            {
                new Product { ProductID =1, Name ="Product 1", Category = "Category 1", Description ="Description 1", Price = 10m},
                new Product { ProductID =2, Name ="Product 2", Category = "Category 1", Description ="Description 2", Price = 20m},
                new Product { ProductID =3, Name ="Product 3", Category = "Category 1", Description ="Description 3", Price = 30m},
                new Product { ProductID =4, Name ="Product 4", Category = "Category 2", Description ="Description 4", Price = 40m},
                new Product { ProductID =5, Name ="Product 5", Category = "Category 2", Description ="Description 5", Price = 50m},
                new Product { ProductID =6, Name ="Product 6", Category = "Category 2", Description ="Description 6", Price = 50m}
            };
            //We are Delaying the Execution for 1 Seconds to get the Data from the database
            await Task.Delay(TimeSpan.FromSeconds(1));
            return products.Take(count).ToList();
        }
    }
}
View Component Server-Side File in ASP.NET Core MVC:

Now, we need to create the view component server-side file. In the project, we can add the server-side file at any location (let’s say /ViewComponents folder). So, in the project root directory, create a folder with the name ViewComponents. Suppose the name of the view component server-side file is TopProducts; then we must add a suffix ViewComponent to its name. Hence, the final name of the view component server-side file will be TopProductsViewComponent.

We typically create a class that inherits from ViewComponent. It contains the logic to generate the content. This class can return a view (HTML) using the View method, similar to how actions in controllers work. The Invoke Method is the entry point for the View Component, which can be named Invoke or InvokeAsync for asynchronous operations. This method contains the logic to generate the data and optionally select a view to render it.

So, create a class file named TopProductsViewComponent.cs within the ViewComponents folder and copy and paste the following code. The code is self-explained, so please read the comment line for a better understanding.

using Microsoft.AspNetCore.Mvc;
using ViewComponentInMVC.Models;
namespace ViewComponentInMVC.ViewComponents
{
    //Create a Class, and it should inherit from ViewComponent class
    public class TopProductsViewComponent : ViewComponent
    {
        //The Invoke method for the View component
        public async Task<IViewComponentResult> InvokeAsync(int count)
        {
            // Your logic for preparing data
            ProductRepository productRepository = new ProductRepository();
            var products = await productRepository.GetTopProductsAsync(count);
            return View(products);
        }

        //public IViewComponentResult Invoke(int count)
        //{
        // // Your logic for preparing data
        // ProductRepository productRepository = new ProductRepository();
        // var products = productRepository.GetTopProductsAsync(count).Result;
        // return View(products);
        //}
    }
}
In the above example:
  • TopProductsViewComponent: The TopProductsViewComponent is inherited from the ViewComponent class. This inheritance makes TopProductsViewComponent a View Component, providing it with the capabilities to execute logic and return a view for rendering.
  • InvokeAsync Method: The InvokeAsync method is the entry point for the View Component and can be called when the component is invoked from a Razor view. The method is asynchronous, allowing for non-blocking I/O operations, such as database calls.
  • return View(products);: Returns a view for rendering, passing items as the model. The View method is a helper method inherited from ViewComponent, and it looks for a Razor view that matches the View Component’s name. The items model will be passed to the view, which can then be used to render HTML.
View Component Client-Side File in ASP.NET Core MVC:

We are using the ASP.NET Core MVC Application and want to invoke the View Component from a view file. Hence, we need to place the client-side file at the following location /Views/Shared/Components/{ViewComponentName}/{ViewName}.cshtml. In our example, the View Component Name is TopProducts, and the view name is going to be Default.cshtml. So, we need to create the View in the following location.

/Views/Shared/Components/TopProducts/Default.cshtml

Once you create the Default.cshtml view file, your Views folder should look as shown below.

View Component Client-Side File in ASP.NET Core MVC

Now, open Default.cshtml view file and then copy and paste the following code into it.

@model IEnumerable<Product>
<div class="row">

    <div>
        <h4>Product Details</h4>

        <table class="table">
            <tr>
                <th>
                    ProductID
                </th>
                <th>
                    Name
                </th>
                <th>
                    Category
                </th>
                <th>
                    Description
                </th>
                <th>
                    Price
                </th>
            </tr>

            @foreach (var product in Model)
            {
                <tr>
                    <td>
                        @product?.ProductID
                    </td>
                    <td>
                        @product?.Name
                    </td>
                    <td>
                        @product?.Category
                    </td>
                    <td>
                        @product?.Description
                    </td>
                    <td>
                        @product?.Price
                    </td>
                </tr>
            }
        </table>
    </div>
</div>

With this, our view component is completed and ready to use.

Invoking the View Component in ASP.NET Core MVC:

Now, we need to invoke it from another view file. So, modify the Index.cshtml file of Home Controller as follows. Here, TopProducts is the name of the View Component, and the count is the parameter with a value of 3. You can assign any value to the count parameter. If you check the View Component CS class file, you will see the InvokeAsync or Invoke method taking one integer parameter named count, and here, we pass a value 3 to that count parameter.

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    @await Component.InvokeAsync("TopProducts", new { count = 3})
</div>

With the above changes, run the application, and you should get the following output.

Invoking the View Component in ASP.NET Core MVC

How Does View Component Work in ASP.NET Core MVC?
  • Invocation: View Components can be invoked from a view by calling the Component.InvokeAsync method, specifying the name of the View Component and any required parameters.
  • Execution: When invoked, the runtime finds the corresponding View Component class and executes its Invoke or InvokeAsync method. This method can perform actions like fetching data and then preparing a model to be passed to the view.
  • Rendering: After the Invoke or InvokeAsync method is executed, the framework renders the View Component’s view, passing it into the model. The rendered HTML is then included in the parent view’s output.
Invoke a View Component from a view file using Tag helper:

Please update the ViewImport file as follows to include the required tag helpers. Here, ViewComponentInMVC is the project name.

@using ViewComponentInMVC
@using ViewComponentInMVC.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, ViewComponentInMVC
@addTagHelper *, ViewComponentInMVC.TagHelpers

Now, if you want to invoke the View Component using Tag Helper, then modify the Index.cshtml file of the Home controller as follows:

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <vc:top-products count="3"></vc:top-products>
</div>
View Components Real-Time Examples in ASP.NET Core MVC:

To avoid code duplication in ASP.NET Core MVC Web Applications, the View Components can be used in various areas such as the Navigation Menus, Login Panel, Billing and Shipping Address, Shopping Cart, etc. View components can be used to create the following features:

  • Login Panel.
  • Dynamic Navigation Menu (Based on role etc.).
  • Get some related data for a page. (Like Related posts, Related books).
  • Shopping Cart.
  • Shipping and Billing Address.
  • Any content visible on the side of the Web Page, etc.

View Component vs. Partial View in ASP.NET Core MVC

In ASP.NET Core MVC, View Components and Partial Views are used to create reusable pieces of Web UI, allowing developers to avoid duplicating markup across different views. However, they serve different purposes and come with their own features, making them suitable for different scenarios.

View Component in ASP.NET Core MVC

View Components are intended for more complex scenarios where you need to execute some logic before rendering the HTML. They are a combination of a C# class that handles the logic and a Razor view that generates the HTML markup. View Components are not part of the MVC request life cycle, which means they cannot directly respond to HTTP requests. Instead, they are invoked from within a view and can be used to render a portion of a page’s response with its own logic.

View Components are intended to be used in situations where you need a component that can perform actions, not just display static HTML. For example, a View Component might display a dynamically generated menu, a shopping cart summary, or widgets that display complex data.

Partial View in ASP.NET Core MVC

Partial Views, on the other hand, are more straightforward. They are essentially segments of Razor markup that can be rendered within other views. Unlike View Components, Partial Views do not have their own logic. They depend on the data provided to them by the view that renders them, typically through model binding or ViewData/ViewBag.

Partial views are best for static or markup-heavy fragments without additional processing or data fetching. They are also best for static content reused in multiple places, such as headers, footers, or reusable forms.

Key Differences Between View Component and Partial View ASP.NET Core MVC
  • Complexity and Functionality: View Components are more complex and can encapsulate both logic and rendering, making them suitable for components that require server-side processing. Partial Views are better for scenarios where you need to refactor or reuse the visual parts of views without additional logic, i.e., ideal for static content.
  • Invocation: View Components are invoked from views or layouts using C# code, can accept parameters, and can be considered more like mini-controllers with their own logic. On the other hand, Partial Views are typically invoked with Html.Partial or Html.RenderPartial methods in Razor syntax rely on the parent view’s model or ViewData for data.

In the next article, I will discuss Razor View Syntax in ASP.NET Core MVC Applications with Examples. In this article, I will explain View Components in ASP.NET Core MVC Applications with Examples. I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *