top of page

Ultimate Guide to View Components in ASP.NET Core

View components play a pivotal role in enhancing the dynamism and interactivity of web pages in ASP.NET Core applications. They offer a versatile approach to create and render reusable UI components, significantly improving code maintainability and reusability.

View Components in ASP.NET Core

In this comprehensive guide, we'll explore view components in ASP.NET Core. You'll gain a deep understanding of what view components are and why they matter, how to create and use view components effectively, along with its benefits and limitations.


By the end of this article, you'll be armed with the knowledge and skills to harness the full potential of view components, elevating your ASP.NET Core projects to new heights of functionality and elegance.


Table of Contents:

Why View Component is Introduced?

Difference between View Component and Partial Views in ASP.NET Core

When to use View Component

Limitations

STEP 1: Create a Class

STEP 2: Implement a Method

STEP 3: Create a view file for a View Component

What is Tag Helper

Benefits of invoking using Tag Helper


What is a View Component in ASP.NET Core?

A view component in ASP.NET Core is a reusable, self-contained UI component that can be rendered in views. It is similar to a partial view, but it offers a number of advantages, including:

  • View components can be invoked from any view, regardless of whether the view is associated with a controller or not.

  • View components can be parameterized, which makes them more flexible and reusable.

  • View components can have their own logic, which makes them more powerful than partial views.


Why View Components is introduced?

View components were introduced in ASP.NET Core to address some of the limitations of partial views. Partial views are a great way to reuse UI elements, but they have a few drawbacks:

  • Partial views can only be invoked from views that are associated with a controller.

  • Partial views cannot be parameterized.

  • Partial views cannot have their own logic.

View components were introduced to overcome these limitations. View components can be invoked from any view, can be parameterized, and can have their own logic. This makes view components more flexible and reusable than partial views.


Difference between View Component and Partial Views in ASP.NET Core:

View components and partial views are both ways to render reusable UI elements in ASP.NET Core. However, there are some key differences between the two:

Feature

View Component

Partial View

Can be invoked from any view

Yes

No

Can be parameterized

Yes

No

Can have their own logic

Yes

No

Can be used to render UI elements that are shared across multiple views

Yes

Yes

Can be used to render more complex UI elements

Yes

Yes

Can only be invoked from views that are associated with a controller

No

Yes

Overall, view components are more flexible and powerful than partial views, but they can also be more complex to implement.


When to use View Components

In ASP.NET Core, View components should be used when you need to create a reusable, self-contained UI component that can be rendered in any view. Some common examples of view components include:

  • Headers and footers

  • Navigation menus

  • Product catalogs

  • Shopping carts

  • Social media buttons

  • Login forms

Limitations:

View components do have some limitations, including:

  • View components can be more complex to implement than partial views.

  • View components can have a performance impact if they are not used carefully.

Overall, view components are a valuable tool for developing ASP.NET Core applications. They offer a number of benefits, including modularity, reusability, encapsulation, and flexibility.


In case you missed, read:


How to create View Components

Here, we provide a step-by-step guide to help you create and use view components in ASP.NET Core.


STEP 1: Create a Class

To create a class in a view component in ASP.NET Core, you can use any of the following methods:

  • Deriving from the ViewComponent class.

  • Decorating a class with the [ViewComponent] attribute.

  • Deriving from a class with the [ViewComponent] attribute.

  • Creating a class where the name ends with the suffix ViewComponent.

The following example shows how to create a view component class using each of these methods:

// Deriving from the ViewComponent class.
public class MyViewComponent : ViewComponent 
{     
    public async Task<IViewComponentResult> InvokeAsync()     
    {         
        return View();     
    } 
}  

// Decorating a class with the [ViewComponent] attribute. 
[ViewComponent] 
public class MyViewComponent 
{     
    public async Task<IViewComponentResult> InvokeAsync()     
    {         
        return View();     
    } 
}  

// Deriving from a class with the [ViewComponent] attribute. 
[ViewComponent] 
public class MyViewComponentBase 
{     
    public async Task<IViewComponentResult> InvokeAsync()     
    {         
        return View();     
    } 
}  

public class MyViewComponent : MyViewComponentBase 
{ 
}  

// Creating a class where the name ends with the suffix ViewComponent.
public class MyViewComponentViewComponent 
{     
    public async Task<IViewComponentResult> InvokeAsync()     
    {         
        return View();     
    } 
} 

Rules for creating view component classes:

  • View component classes must be public, non-nested, and non-abstract.

  • The view component name is the class name with the ViewComponent suffix removed. It can also be explicitly specified using the Name property.

  • View component classes support constructor dependency injection.

  • View component classes do not take part in the controller lifecycle, so filters cannot be used in view components.

  • To prevent a class that has a case-insensitive ViewComponent suffix from being treated as a view component, decorate the class with the [NonViewComponent] attribute.

Once you have created a view component class, you need to implement the InvokeAsync() or Invoke() method. This method is responsible for rendering the view component.


STEP 2: Implement a Method

A view component defines its logic in an InvokeAsync or Invoke method.

  • The InvokeAsync method returns a Task<IViewComponentResult>, which means that it can be used to render view components asynchronously. This is the recommended method for rendering view components, as it allows the ASP.NET Core runtime to optimize the rendering process.

  • The Invoke method returns an IViewComponentResult and does not support asynchronous rendering. This method is typically used for rendering simple view components that do not require any asynchronous processing.

The parameters of a view component method come directly from the invocation of the view component, not from model binding. This means that you cannot use the @model directive in a view component view to access model data. Instead, you must pass the model data to the view component method as a parameter.


In ASP.NET Core, a view component never directly handles a request. Instead, it is typically invoked in a view. This means that you cannot access the HTTP request context in a view component method.


View component methods are overloaded on the signature rather than any details from the current HTTP request. This means that you can have multiple view component methods with the same name but with different signatures. This can be useful if you need to render the same view component with different parameters.


Here is an example of a simple view component method:

public async Task<IViewComponentResult> InvokeAsync() 
{     
    // Initialize the model.
    var model = new MyViewModel();      
    
    // Pass the model to the view.
    return View(model); 
} 

This view component method initializes a MyViewModel instance and passes it to the view. The view can then access the model data using the model property.


STEP 3: Create a view file for the view component

To create a view file for a view component, you can follow these steps:

  1. Create a new file in the Views/Shared/Components/{View Component Name}/{View Name} folder.

  2. Give the file the .cshtml extension.

  3. Add the Razor code to render the view component.

The following example shows a simple view file for a view component in ASP.NET Core:

@model MyViewModel  

<h1>My View Component</h1>

<p>This is my view component.</p>

<p>@model.Name</p>

This view file renders a simple heading and paragraph. The model property contains the model data that was passed to the view component method.


You can also use Razor syntax in view component views to render dynamic content. For example, the following view file renders a list of items from a model:

@model IEnumerable<MyItem>

<h1>My View Component</h1>
<ul>     
    @foreach (var item in model)     
    {         
        <li>@item.Name</li>     
    } 
</ul>

This view file renders a list of items from the model property. The @foreach loop iterates through the list and renders an <li> element for each item.


How to Invoke View Component?

To invoke a view component in ASP.NET Core, you use the Component.InvokeAsync() method in a view or controller. This method takes two parameters: the name of the view component and an anonymous type containing parameters to pass to the view component.


The code snippet you provided shows how to invoke the PriorityList view component from the Views/ToDo/Index.cshtml view file. The maxPriority and isDone parameters are passed to the view component using an anonymous type.


The following code shows how to invoke the PriorityList view component from a controller action:

public class ToDoController : Controller {     
    public IActionResult Index()     
    {         
        var maxPriority = 10;         
        var isDone = false;          
        
        ViewData["maxPriority"] = maxPriority;         
        ViewData["isDone"] = isDone;          
        
        return View();     
    }      
    
    public IActionResult PriorityList(int maxPriority, bool isDone)     
    {         
        // Render the PriorityList view component.
        return ViewComponent("PriorityList", new { maxPriority, isDone });     
    } 
} 

When the PriorityList view component is invoked, it will render the Views/Shared/Components/PriorityList/Default.cshtml view file. This view file can contain any HTML, CSS, and JavaScript code that you need to render the view component.


How to Invoke View Component as a Tag Helper?

A view component can be invoked as a Tag Helper. This allows you to use view components in your views in a more concise and declarative way.


What is a Tag Helper?

A Tag Helper is a server-side code construct that enables you to create and render HTML elements in Razor files. Tag Helpers are written in C# and can target HTML elements based on element name, attribute name, or parent tag.


Why use Tag Helpers?

Tag Helpers offer a number of advantages over traditional HTML Helpers, including:

  • An HTML-friendly development experience: Tag Helper markup looks like standard HTML, making it easy for front-end designers to edit Razor views.

  • A rich IntelliSense environment for creating HTML and Razor markup: Tag Helpers provide a more powerful and informative IntelliSense experience than HTML Helpers.

  • A way to make you more productive and able to produce more robust, reliable, and maintainable code: Tag Helpers can encapsulate complex server-side logic, making your code more modular and easier to maintain.

Examples of Tag Helpers

Some examples of built-in Tag Helpers include:

  • ImageTagHelper: Appends a version number to the image name, so clients are guaranteed to get the current image.

  • AnchorTagHelper: Generates links that are accessible to users with disabilities.

  • LabelTagHelper: Generates labels for form fields that are associated with the form fields using the for attribute.

  • InputTagHelper: Generates input fields that are pre-populated with data from the model.

To invoke a view component as a Tag Helper, you use the following syntax:

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

The [view-component-name] placeholder is replaced with the name of the view component that you want to invoke. The parameter1 and parameter2 attributes are optional and are used to pass parameters to the view component.


The following example shows how to invoke the PriorityList view component as a Tag Helper:

<vc:priority-list max-priority="10" is-done="true">
</vc:priority-list>

This will render the PriorityList view component with the maxPriority and isDone parameters set to 10 and true, respectively.


Registering a view component as a Tag Helper

Before you can invoke a view component as a Tag Helper, you must register the assembly containing the view component. To do this, add the following @addTagHelper directive to the _ViewImports.cshtml file:

@addTagHelper *, MyWebApp 

Replace MyWebApp with the name of the assembly containing the view component.


The InvokeAsync method

The InvokeAsync() method is used to invoke a view component asynchronously. To use this method, you pass the name of the view component and an object containing the parameters to the method.


The following example shows how to invoke the PriorityList view component using the InvokeAsync() method:

@await Component.InvokeAsync("PriorityList",                  
        new {                       
                maxPriority =  ViewData["maxPriority"],                      
                isDone = ViewData["isDone"]  }                  
        ) 

This will render the PriorityList view component with the maxPriority and isDone parameters set to the values of the ViewData["maxPriority"] and ViewData["isDone"] properties, respectively.


Benefits of using view components as Tag Helpers

There are several benefits to using view components as Tag Helpers:

  • Conciseness: Tag Helpers provide a more concise way to invoke view components. Instead of using the Component.InvokeAsync() method, you can simply use the vc: element.

  • Declarativeness: Tag Helpers allow you to invoke view components in a more declarative way. You can specify the view component and its parameters using attributes, rather than having to write code.

  • Reusability: Tag Helpers can be reused across multiple views. This can help to improve the maintainability and reusability of your code.


Conclusion

View components in ASP.NET Core are a game-changer for crafting dynamic and reusable UI components in web applications. They simplify development, enhance code maintainability, and offer endless possibilities for creating interactive web pages. With this powerful tool in your toolkit, you're well-equipped to take your ASP.NET Core projects to the next level.


Happy coding!

bottom of page