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 View Components in ASP.NET Core MVC?
  2. Why should we use View Components in ASP.NET Core MVC?
  3. How to use View Components in ASP.NET Core MVC Application?
  4. Advantages of using View Components.
  5. What is the difference between View Components and Partial Views?
What are the View Components in ASP.NET Core MVC?

The View Component is a unique tool that enables the display of data (view + data) on a view file independently from the entire HTTP Life Cycle.

View Components are a powerful feature in ASP.NET Core MVC that allows us to create and render reusable, self-contained components within our views. View Components provide a way to encapsulate UI and related logic, which facilitates building modular and easy-to-maintain applications. View Components are particularly useful when we need more flexibility and interactivity than what partial views provide in ASP.NET Core MVC Applications.

View Components serve as fundamental components within ASP.NET Core Application. They render a response, but not an entire response. Instead, they generate a piece of the response. If this is not clear now, don’t worry; once we discuss the example, you will understand this concept.

What Features Can We Create Using View Components in ASP.NET Core?

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. So, in simple words, we can say that View Components function like a Web Part by combining both Business Logic and UI design into a reusable package that can be reused in multiple parts of the Web Application.

View components are developed to serve a very important role in ASP.NET Core Web Applications. 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.
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.

Location1: 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}

Location2: 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}

Location3: 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 some 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?

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 by 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

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

Product Model:

First, create a class file with the name Product.cs within the Models folder and then copy and paste the following code into it. This is going to be our model, which is going to 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 with the name ProductRepository.cs within the Models folder and then copy and paste the following code into it. The code for getting top products from the database is written in ProductRepository.cs file. You will get the data from the database in real-time, but here, we have hard-coded the data.

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 derives from ViewComponent class to create a View Component. This class contains methods that are responsible for the logic and data preparation needed to render the component.

So, create a class file with the name TopProductsViewComponent.cs within the ViewComponents folder and then copy and paste the following code into it. The following code is self-explained, so please go through 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 books = await productRepository.GetTopProductsAsync(count);
            return View(books);
        }

        //public IViewComponentResult Invoke(int count)
        //{
        // // Your logic for preparing data
        // ProductRepository productRepository = new ProductRepository();
        // var books = productRepository.GetTopProductsAsync(count).Result;
        // return View(books);
        //}
    }
}
View Component Class in ASP.NET Core MVC
  • View component class name ends with the suffix ViewComponent
  • It inherits from the ViewComponent base class
  • It supports dependency injection like a razor page or an MVC controller.
  • A view component does not directly respond to an HTTP request. It is usually invoked and consumed by a razor page, layout view, or an MVC view.
  • When a view component is invoked, it calls the Invoke method.
  • Invoke() method returns IViewComponentResult.
  • Use InvokeAsync() method if you want to call the View Component asynchronously.
  • View Component follows the MVC design pattern. It initializes a model and passes it to a view by calling the View method.
  • Though it follows the MVC approach, it can be used both in an MVC project and a razor pages project.
View Component Client-Side File in ASP.NET Core MVC:

As we are using ASP.NET Core MVC, and we 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/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.

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

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

With the above changes in place, run the application and get the following output.

Invoking the View Component in ASP.NET Core MVC

Invoke a View Component from a view file using Tag helper:

Now we need to invoke it from another view file using Tag Helper. So, 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>

Note: Currently, invoking View Component using Tag Helper is not working. Please check the below URL for more details.

https://github.com/dotnet/aspnetcore/issues/46740

Advantages of Using View Component in ASP.NET Core MVC:

Using View Components in ASP.NET Core MVC offers several advantages that contribute to better code organization, reusability, and maintainability. Here are some of the key advantages of using View Components:

  1. Modularity and Reusability: View Components enable you to create self-contained, modular components that encapsulate both UI and related logic. These components can be reused across different views, layouts, and even projects, promoting a consistent user experience and reducing code duplication.
  2. Enhanced Separation of Concerns: View Components allow you to separate the logic and data preparation for specific UI components from the main view or layout. This promotes a clearer separation of concerns and improves the maintainability of your codebase.
  3. Isolation and Testability: View Components can be unit tested in isolation, making verifying their behavior and ensuring correctness easier. This level of testing granularity contributes to more reliable and stable applications.
  4. Parameterized Invocation: View Components support parameterized invocation, allowing you to customize their behavior based on the context in which they are used. This enables you to create flexible and dynamic components that adapt to different scenarios.
  5. Dynamic Content Generation: View Components are especially useful when you need to generate dynamic content within your views, such as content that changes based on user interactions or data conditions.
  6. Complex UI Components: View Components provide a more structured approach than partial views when dealing with complex UI components requiring significant logic. They allow you to encapsulate the HTML rendering and the associated logic within a single component.
  7. Code Maintainability: By encapsulating components within View Components, your codebase becomes more organized and easier to maintain. Changes and updates to a specific component can be made within the context of the View Component, reducing the risk of unintended side effects.
  8. Custom Controls: View Components allow you to create custom controls or widgets that are not available out-of-the-box in HTML or standard libraries. This enables you to build tailored and unique user interfaces.
  9. Parallel Development: View Components facilitate parallel development by enabling different teams or developers to work on separate components independently. This can improve overall project efficiency.
  10. Clear Component Contracts: View Components can define clear contracts for the data they require and the output they produce. This makes understanding how to use a particular component and what to expect from it easier.
  11. Tag Helper Integration: ASP.NET Core provides tag helpers specifically designed for View Components, making their invocation more intuitive and readable in Razor views.

Overall, View Components offer a flexible and powerful approach to building modular UI components in ASP.NET Core MVC applications. They contribute to a more maintainable and scalable codebase, allowing you to create rich, interactive, and dynamic user interfaces while maintaining a clean separation of concerns.

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

View Components and Partial Views are both mechanisms for creating reusable components in ASP.NET Core MVC applications, but they have distinct use cases and differences in terms of functionality and capabilities. Here’s a comparison between View Components and Partial Views:

Partial Views:
  • Purpose: Partial Views are primarily used for reusing a portion of a view across multiple views or layouts. They are best suited for rendering static or relatively simple UI components.
  • Scope: Partial Views are more tightly coupled to the main view or layout that includes them. They are typically used for small-scale UI reuse, such as headers, footers, navigation menus, and sidebars.
  • Data Sharing: Partial Views share the same model or ViewData dictionary as the parent view, making them less isolated regarding data sharing.
  • Complex Logic: Partial Views can contain a mix of HTML and Razor code, but they are generally better suited for rendering UI elements rather than complex logic.
  • Testing: Partial Views can be unit tested as part of the parent view, but isolating and testing their behavior independently can be more challenging.
View Components:
  • Purpose: View Components are used to create self-contained, modular components that encapsulate both UI and related logic. They are more powerful and flexible, making them suitable for more complex scenarios.
  • Scope: View Components are designed for larger-scale UI components with associated logic. They can be used to render dynamic, data-driven, and interactive components within your views.
  • Data Sharing: View Components have their own model and data context, which makes them more isolated and self-contained. They can also accept parameters to customize their behavior.
  • Complex Logic: View Components can contain both HTML and logic, making them suitable for rendering complex UI components with dynamic behavior, data manipulation, or calculations.
  • Testing: View Components can be unit tested in isolation, which improves testability and helps ensure the correctness of their behavior.
Which One to Choose:

Choose Partial Views when you need to reuse simple UI elements across multiple views, and the component doesn’t require much logic or data manipulation. Use View Components to create more complex, interactive, or dynamic components with encapsulated logic and data context.

In summary, Partial Views are well-suited for basic UI reuse within a view or layout. At the same time, View Components offer a more advanced and powerful approach for creating modular and maintainable UI components with associated logic. The choice between the two depends on the complexity and requirements of the component you’re building.

View Components provide a way to build dynamic, interactive, and self-contained UI components in ASP.NET Core MVC applications. They are a valuable tool for creating modular and maintainable code and can greatly enhance the flexibility and organization of your application’s user interface.

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

Leave a Reply

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