ORGANIZE VIEWS INTO COMPONENTS

CREATE CUSTOM HELPER TAGS

NET CORE

Creating a component is important because then we can reuse that logic in the Views that make up the application. We will have created something that is testable in isolation, in fact as we will see we can create automated tests to prove that each of our components works.

Componenti
Component

Let’s see how to write the Tag Helper containing the rating star logic.

RatingTagHelper

There are conventions to follow, the component being named RatingTagHelper, in the View Razor the tag will be rating. When the Razor engine in the HTML code finds a TagHelper it does a kind of Model Binding, passing the ball to the component with the values it needs. @Course.Rating in our case, automatically valuing the Value property of the TagHelper. In its redefined method Process creates the necessary C# logic and in the output parameter writes the HTML. Look at the code found in the Customization/TagHelpers directory as the other two components were written. The code is annotated.

Index.cshtml
Tag Helper personalizzati

I VIEW COMPONENT

There are situations where we need to generate a conspicuous HTML block, such as course paging.

Paginazione
ViewComponent

A View Component is responsible for generating a small portion of the interface, it can decide which View to return. We can compare it to a Controller with its own Action Invoke and respective View. The difference is that a Controller handles http requests, while a View Component is used to generate markup. Supports Dependency Injection.

Struttura cartelle

There are naming conventions to be observed here as well; the name of the PaginationBar component must be followed by ViewComponent to make it clear that it is that component. The View by creating it within the Shared directory will be visible everywhere, facilitating code reuse.

Creare View Component

FOLLOW THE PRINCIPLE OF INTERFACE SEGREGATION

To encourage code reuse, we cannot make the component depend on a concrete implementation, which creates strong coupling and makes the component unusable for other purposes. Better to provide the Invoke parameter with an interface. IPaginationInfo.

IPaginationInfo

This interface has all the values we need for paging, no more and no less. Let us see how the properties were enhanced.

CourseListViewModel

CREATE A PARTIAL VIEW

When you want to encapsulate a lot of HTML code in a component, you use a partial view.

Partial view
Struttura
Partial_line

LINK TO CODE ON GITHUB

GITHUB

Download the section14 code or clone the GITHUB repository to have all sections available in your favorite editor.