TagHelper syntax for View Components - Day 3 - 24 days of "Front-end Development with ASP.NET Core, Angular, and Bootstrap"

It's the 3rd of December, and today I want to talk about View Components, showing how they can be added to a page using the Tag Helper syntax.

This is covered more in detail in the first chapter of my upcoming book Front-end Development with ASP.NET Core, Angular, and Bootstrap.

What are View Components

View Components is something introduced in ASP.NET Core, and they are used to encapsulate both UI and logic for reusable portions of pages: we can see them as the new version of the Child Actions (which have been removed from the MVC framework in ASP.NET Core). A big improvement if you ask me.

In it's simplest implementation, a View Component is just a class which extends ViewComponent and implements the method Invoke which returns a IViewComponentResult. This renders a view which is by convention stored in \Views\Shared\Components\{component_name}\Default.cshtml.

As very simple view component that shows a counter to a specific date can be implemented with few lines of code.

Here the component

public class CountdownViewComponent: ViewComponent
{
    public IViewComponentResult Invoke(DateTime to, string eventName)
    {
        var today = DateTime.Today;
        var diff = (to - today).TotalDays;
        var model = $"{diff} days to {eventName}";
        return View<String>(model);
    }
}

And it's view

@model string
<b>It's @Model</b>

How to include the View Component into a view

The original way of including the view component is a view is by using the Component class specifying the name of component (as string) and an anonymous object with the parameters:

@await Component.InvokeAsync("Countdown", new {to = new DateTime(2017,12,15), eventName="Christmas"})

But this syntax is not easy to use and not discoverable as it relies on magic strings and on the developer needs to know the exact name of parameters.

There is also the TagHelper syntax, which is much easier.

<vc:countdown
    to="new DateTime(2017,12,25)"
    event-name="Christmas">
</vc:countdown>

And also comes with Intellisense:

View Component Intellisense

For this to work, also remember to register you View Components as tag helpers. In the _ViewImports.cshtml file add the following line (where projectName is the name of your project, actually the assembly name in which your project is compiled):

@addTagHelper *, projectName

If you want to learn more about View Components, Tag Helpers and much more, consider pre-ordering a copy of Front-end Development with ASP.NET Core, Angular, and Bootstrap and get it as soon as it hits stores.

If you want to see more of what is coming, come back tomorrow for more tips.