How to use View Component on a Razor Page

Razor Pages is a new concept in Asp.Net Core. This discussion is not about how to develop Razor Pages or how to use Razor Pages. Microsoft has provided has provided great introduction and walk though on this topic in their documentation. You can visit following link for more information.

Introduction to Razor Pages in ASP.NET Core

I am going to talk about changes that have happened in the area of View Components with Razor Pages. The fundamentals of developing View Components remain the same.

  • Implement a public class that derives from ViewComponent as base class
  • Implement Invoke or InvokeAsync method in your view component class. This method is responsible for return view result

View Component View File

There is small update on path where Asp.Net Core framework will look for view file for a view component. In the documentation you will find that the runtime searches for the view in the following paths:

  • /Pages/Components/{View Component Name}/{View Name}
  • /Views/{Controller Name}/Components/{View Component Name}/{View Name}
  • /Views/Shared/Components/{View Component Name}/{View Name}

First item in above list is change related to Razor Pages. New path has been added to search path.

Include View Component In Razor Page

There is not much of a change related to how you will include a View Component in Razor Pages. You can following methods to include View Component.

Tag Helper

You can use tag helper for your view component to include view component on Razor Page. I have a footer view component that i am including in my page.

<div class="container body-content">
        @RenderBody()
        <hr />
        <vc:footer></vc:footer>
    </div>

Just to refresh your memory, you will need to use @addTagHelper at top of page where you are including tag helper for view component or my preferred way is to include in _ViewImports.cshtml.

@addTagHelper *, Qms.Web

Explicit Invoke On Page

Another way to include View Component on Razor Pages will be to call Invoke or InvokeAsync for your component.

@await Component.Invoke("Qms.Web")

Go Razor Pages!

Search

Social

Weather

22.6 °C / 72.7 °F

weather conditions Clouds

Monthly Posts

Blog Tags