ASP.NET 5 comes with another version of ASP.NET MVC that is ASP.NET MVC6.View Component is another very powerful got added with MVC 6. If you have not already gone through with this feature, you might just keep guessing about it and may correlate with multiple things. But this feature when you go through, you will enjoy it.

Before discussing this, How many of used Child Actions or know about that?

If you have used that you must have find it bit nasty. Child Actions are like a normal action but it can not be called by directly from url instead it is called from a view. The key usage of Child Action, when we want to reuse some part of UI at multiple places then we create a child action and use it at multiple places. One of the key issues was that with this, it makes another request to the server to call the action method, by going through the whole life cycle which makes the application slow. Also It can not be invoked asynchronously.

View Component provides us capability to write a component that generates a part of the UI similar to Partial View . It can be reused on different places based on the requirement. One of the classic example could be a shopping cart that is visible to user on every page and many similar others. Now you no longer need Child Action after using it.

So How to create a ViewComponent ?

There are two part of that

1- Create a class that derives from class ViewComponent

2- A razor view which will be using the ViewComponent class by calling its method.

You can think of the class as a mini-controller and another one as a view. Let’s create an example,

Say I want to show Top Users of the website and showing them on each page in a section. So let’s create a View Component Class

1- Note here that the class name ends with ViewComponent and the name would be TopUsers only similar to controllers. If you don’t want to add this suffix then you can provide an attribute on the class as [ViewComponent(Name = “TopUsers”)] then you can give whatever name you want.

2- Here Invoke would be fired and for each View Component instance. We can pass as many parameters as we require. There is async version of this method is also available which can be very useful if you are connecting to some third party component or you know this would be long process.

We have already created the class. Now lets create the View. Here we need to follow certain structure to create the View. For this example, I have created a MVC controller named as DemoController and created an Index view. As We are going to use the View Component here, we need to create the folder structure like Views\<ControllerName>\Components\<ViewComponentName>\. For this example it is as Views\Demo\Components\TopUsers\. So we need to create a view in this folder as Default.cshtml. It is as