6 Reasons To Use ViewComponents in ASP.NET 5

When using ASP.NET ViewComponents, there's a number of benefits to make your application more modular. Today, we review those benefits based on experience.

Written by Jonathan "JD" Danylko • Last Updated: • Develop •

Car engine

ViewComponents were first introduced back in 2016 with ASP.NET Core and what I consider to be the logical evolutionary mix of HTMLHelpers and Partial views.

Partial views were merely the templates based on an object passed from a controller where HTMLHelpers would implement business rules so not to make the HTML a bunch of 'if..then' statements. As the name implies, you could also create HTML inside of the HTMLHelper, but that would mean you have two problems now. :-)

Why ViewComponents?

While ViewComponents are more server-side than client-side, they still provide a simple means to an end of componentizing an application.

I know some developers hear the word "component" and immediately switch their thinking over to the client-side. This makes sense since web components have tenure and include <script>, <style>, and <template> in one package.

I see ViewComponents similar to a client-side web component.

  • ViewComponents use C# where Web Components use JavaScript
  • ViewComponents use Views (or HTML) where Web Components use templates (also HTML)

The tricky part is the styling with CSS. While you can implement styling through the model, it still makes the component hard to work with when updating styles (change CSS, then "recompile" your CSS...?)

However, are inline styles coming back? Google seems to be loosening their hold on using inline styles when optimizing pages for Search Engine Optimization (SEO) and performance reasons.

While I may have digressed a bit, this is one subject I want to cover in an upcoming post.

Benefits of ViewComponents

Some examples of ViewComponents could be a menu system, headers/footers, data entry, or any other modular approach.

These types of subsystems could be packaged into ViewComponents and used in other applications.

This brings us to the benefits of ViewComponents and why they should be used more in ASP.NET development. 

1. ViewComponents provide a Separation of Concerns

The SOLID principles should also apply to your ViewComponents. Your ViewComponent should work with a model and only a model.

It's similar to the old ASP.NET MVC Controllers. Once the train (your models) has left the station (controller passing it to the view), no external calls are allowed.

No database calls.

No API calls.

Simply using business rules and data to populate the View. This encapsulates the data required and the behavior of the ViewComponent so you can use it anywhere in your application. Almost like a "pass me the model and I'll take care of this for you."

For example, if you have a view and want to display an uploaded file, you could create a ViewerViewComponent. By passing in a file object as your model, you could create a DocumentViewComponent meant for document files and an ImageViewComponent for images.

Your business rule would determine the file type and the ViewComponent could load a different view based on the type.

If there is an issue with the DocumentViewComponent, you simply work on the DocumentViewComponent to make it work without affecting anything else.

This is what makes a ViewComponent attractive.

2. ViewComponents Allow You To Create New HTML Tags

What if you were able to create your own industry-specific HTML language?

ViewComponents can also be camouflaged as TagHelpers allowing you to create your own HTML tags.

For example, if you were building a hotel application, some tags would include a <calendar>, <availability>, and <room-gallery>. These would look like brand new tags in HTML, but ASP.NET would render them on the server and create the HTML based on the data model fed to them.

The ViewComponents would be called CalendarViewComponent, AvailabilityViewComponent, and RoomGalleryViewComponent, respectively.

There is a caveat to this approach though. Based on my experience, if you nest ViewComponents inside other ViewComponents as TagHelpers, the children will not render.

The easiest approach is to simply use the Component.Invoke instead of the TagHelper syntax.

3. ViewComponents Allow Business Rules

With Partials, you can pass data into the view, but the partial doesn't have the ability to introduce any business rule capabilities. It's simply a template receiving a model.

Ok, wait...I kind of lied.

If your partial does require any kind of business rule, you introduce C# into your HTML view (@if()).

Call me a purist, but this muddies your partial template and doesn't provide a clean way to implement business rules. Basically, your C# is in my HTML and this goes back my first benefit regarding separation of concerns.

With a C# backend tied to a ViewComponent, this gives you more control of what to display in an isolated component.

4. ViewComponents Render A Chunk

By default, ViewComponents only render a chunk of the view instead of an entire response. This makes the component independently render faster.

With partials, we are relying on a controller. ViewComponents are, by nature, executed in a more isolated approach with no dependencies.

5. ViewComponents are Easy to Unit Test

Unit testing a ViewComponent is easier than testing...say...a partial with business logic in the View.

The process is as follows:

  1. Arrange - Instantiate the ViewComponent
  2. Act - Call the .Invoke() method (with an optional parameter)
  3. Assert - Compare the component's ViewData.Model coming back and see if it's the right type and values are correct

While ViewComponents are isolated by nature, this makes unit testing far easier. 

6. ViewComponents Could Be Tested For Responsive Design...sorry, Container Queries

Since your view is isolated to a single ViewComponent, there's no reason why you couldn't add some Bootstrap or responsive classes to the view to test it for responsive design.

Remember, the view can adjust to whatever device is available.

It's also easier to test the ViewComponent in an isolated web page to verify the responsive design.

Uhh...I mean Container Queries (Responsive Design is soo 2019).

Conclusion

I've been using ViewComponents in my applications since they were introduced in 2016. While they've obviously evolved, I'm always trying to update and find other ways to expand my library by creating industry-specific tags.

As I mentioned above, the one hiccup with ViewComponents has always been styling. While styling is a bit of a stretch and a little tedious when attaching JavaScript, it makes sense to create a style/script for each ViewComponent based on a proposed structure. Therefore, it makes sense to use a Task Runner at design-time.

I still feel the benefits of using ViewComponents simply outweigh the drawbacks.

Have you created any ViewComponents? What do you think is the best feature of ViewComponents? Post your comments below and let's discuss.

Did you like this content? Show your support by buying me a coffee.

Buy me a coffee  Buy me a coffee
Picture of Jonathan "JD" Danylko

Jonathan Danylko is a web architect and entrepreneur who's been programming for over 25 years. He's developed websites for small, medium, and Fortune 500 companies since 1996.

He currently works at Insight Enterprises as a Principal Software Engineer.

When asked what he likes to do in his spare time, he replies, "I like to write and I like to code. I also like to write about code."

comments powered by Disqus