During the building process, files with the extension razor
are transformed into files with the extension .cs
. Because the class name is automatically inferred from the filename in our razor
files, we need a method to specify when the class that is generated additionally should be a generic one. The @typeparam
directive in our class allows us to define one or more generic parameters that are delimited by commas. The generic class can be beneficial when combined.
In this example, I will show you how to create a reusable card in blazor.
First, we need to make a Card.razor file in the root folder and mark it as a generic class with a single generic parameter called ‘T’. We’ll also add a property called [Parameter]
that expects an IEnumerableT>
.
@typeparam T
@foreach (var item in Items)
{
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Card Title</h5>
<p>@ItemTemplate(item)</p>
<a href="#" class="card-link">Card link</a>
<a href="#" class="card-link">Another link</a>
</div>
</div>
}
@code {
[Parameter]
public List<T> Items { get; set; }
[Parameter]
public RenderFragment<T> ItemTemplate { get; set; }
}
Let’s understand the code line by line.
-
@typeparam T
Indicates that this part is generic and has only one generic parameter. namedT
. -
Declares a
[Parameter]
property named Items that is an enumerable property of typeT.
-
Declares a
[Parameter]
the property named ItemTemplate is aRenderFragment<T>
– so we can pass an instance ofTItem
to it and have it give us some rendered HTML to output. -
Iterates over the
Items
property and for each element renders theRenderFragment<T>
named ItemTemplate by passing the current element to it.
How to use
<Card Items="names" T="string" Context="name">
<ItemTemplate>
@name
</ItemTemplate>
</Card>
<Card Items="ints" T="int" Context="i">
<ItemTemplate>
@i
</ItemTemplate>
</Card>
@code {
private List<string> names = new List<string>();
private List<int> ints = new List<int>();
protected override void OnInitialized()
{
names.Add("Card1");
names.Add("Card2");
ints.Add(2);
ints.Add(3);
ints.Add(5);
}
}
As you can see in the above example, I am displaying two cards two times, one for List<string>
and another for List<int>
.