Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Blazor: How to use @typeparam in Code behind? (with workaround)

Tags:

c#

blazor

In a Blazor .razor file you can use @typeparam MyType to use generic parameters. For example:

MyComponent.razor

@typeparam MyType

<SomeHtml />

@code
{
    [Parameter]
    public List<MyType> MyList{ get; set; }
}

So you can call:

<MyComponent MyType="MyTypeABC" MyList="@MyData.MyList" />

But I prefer code behind (razor.cs), how can I use a parameter for type like @typeparam MyType in the razor.cs file?

My current workaround is:

MyComponent.razor

@inherits MyComponentCode<MyType>
@typeparam MyType

MyComponent.razor.cs

public class MyComponentCode<MyType> : ComponentBase
{
    [Parameter]
    public List<MyType> MyList{ get; set; }
}

I miss something like [TypeParameter], but maybe there are better solutions, any ideas? Or maybe it's a general question about "how to use razor @statements in a code behind".


Update from 2020-02-27:

With suggestion from Roger Wolf (see below), a bit better way:

MyComponent.razor

@typeparam MyType

MyComponent.razor.cs

public partial class MyComponent<MyType>
{
    [Parameter]
    public List<MyType> MyList{ get; set; }
}

Call

<MyComponent MyType="MyTypeABC" />
like image 523
StewieG Avatar asked Feb 25 '20 11:02

StewieG


1 Answers

You were pretty close, just need to add partial to the class definition:

using Microsoft.AspNetCore.Components;

namespace BlazorApp1.Components
{
    public partial class MyCustomComponent<T> : ComponentBase
    {
        [Parameter]
        public string Label { get; set; }
    }
}

The Razor part:

@namespace BlazorApp1.Components
@typeparam T

<label>@($"{Label}. Provided type is {typeof(T).Name.ToUpper()}")</label>

The usage (Index.razor):

@page "/"
@using BlazorApp1.Components

<MyCustomComponent T="long" Label="Custom component label" />

This way, you wouldn't need inheriting your component from it, as both become parts of the same class.

like image 177
Roger Wolf Avatar answered Nov 03 '22 10:11

Roger Wolf