pass a System.Reflections.Type in to generic component @typeParam on blazor component

49 Views Asked by At

I want to get my type from the database and then use a type variable to pass the type to the component. The reason why I'm not just strongly typing it is because we want to be able to switch the type in the database and it automatically reflects that in the website. User Server Side Blazor application.

//---GenericComponent---
@typeparam TItem

@code{   
   CustomClass<Titem> CustomClass {get;set;}
}
//---Razor---
@{
   Type type = Type.GetType("DatabaseString");
<GenericComponent TItem="type" />
}

Is there anyway to accomplish this because the alternative that makes the most sense is to do a giant switch case where I call the component and hard code the TItem type using the string from the database as the switch.

1

There are 1 best solutions below

1
Qiang Fu On

You could try pass the list instance to child component. And use Activator to generate list instance.
GenericComponent.razor

@code {
    [Parameter]
    public List<Object> listobj { get; set; }
}
@page "/"
@using System.Reflection
@using System.Collections

<GenericComponent listobj="instance"></GenericComponent>
@code{
    public List<Object> listinstance;
    protected override void OnInitialized()
    {
        Type t = Type.GetType("BlazorApp56.Student", true);
        var listType = typeof(List<>);
        var constructedListType = listType.MakeGenericType(t);
        listinstance = (List<Object>)Activator.CreateInstance(constructedListType);
    }
}