On this Canada Day 2016 weekend I have time to get back to building my own Blog Application. In this post I look at a new feature in ASP.NET Core – View Components. View Components are similar to partial Views but they are much more powerful.
View Components have the same separation of concerns and testability benefits as Controllers and Views. They consist of two parts, the class – usually derived from the ViewComponent base class - and the result it returns - usually a view.
I have incorporated a number of ViewComponents in Naif.Blog
- List – used to render the list of blog posts
- Excerpt – used to render the excerpt or abstract of a single post
- Post – used to render the complete post
- Category List – used to render a list of Post categories
- Tag Cloud – used to render a tag cloud
- Copyright – used to render the copyright
- Disclaimer – used to render the disclaimer
Lets look at one of these ViewComponents – ListViewComponent - to see how its used
The ViewComponent class
The ViewComponent class (like the Controller class) can be a simple POCO but is most often derived from the ViewComponent base class in order to get access to the base classes helper methods and properties.
The InvokeAsync method is used to return an IViewComponentResult. In this case all the method does is to pass the list that is passed in on to the View, but it could also make calls to services passed to component through Dependency Injection, just like an action method in a Controller class.
The ViewComponent View
ViewComponent views are no different from regular views. However, views can only be located in one of two locations
As ViewComponents are meant to be reused, most of the time it makes sense to place ViewComponent views in the Shared folder. As with regular views you can pass a specific named view, but if no name is provided the default is “Default.cshtml”.
So in the case of the ListViewComponent my view is at:
The ListViewComponent’s view simply iterates through the posts in the Model and invokes the ExcerptViewComponent to render the individual excerpts or abstracts.
View Components are a powerful tool especially when building customizable applications. In my previous post I described how to theme your application and by using View Components you can provide totally different layouts built on small discrete components.
The source for Naif.Blog can be found at https://github.com/cnurse/Naif.Blog. If you want to find the state of the repository used in this post then you can find that at the tagged release v0.0.4 (https://github.com/cnurse/Naif.Blog/releases/tag/v0.0.4)