AsM
AsM

Reputation: 195

Passing lists with any type from parent to child component on razor page

I am trying to pass a list from the parent to the child component so that the child component can process with the list.
Then, the user can click the button on the child component to process the list received from the parent.

Error
cannot convert from 'System.Collections.Generic.List<Test.Data.Class1>' to 'System.Collections.Generic.List<System.Type>'

Class

public class Class1
{
    public string name {get; set;} = string.Empty;
    public int id {get; set;} 
}

Parent Razor Page

@if (myList.Any() != false)
{
    <Component1 childList="@myList"/>
}

@code{
    List<Class1> myList = new List<Class1>();
    //add data into myList
    ... 
}

Child Component

<button onclick="@childFunction">Process List</button>

@code{

    [Parameter]
    public List<Type> childList{get; set;} = null!;

    public void childFunction()
    {
         ProcessList(childList);
    }

    public static void ProcessList<T>(List<T> childList)
    {
        ...
    }

}

Upvotes: 0

Views: 337

Answers (1)

The Backer
The Backer

Reputation: 718

If you are adding generic component, then you need to add @typeparam Type in Component1.razor

@typeparam Type
<button onclick="@childFunction">Process List</button>

@code {

    [Parameter]
    public List<Type> childList { get; set; } = null!;

    public void childFunction() => ProcessList(childList);

    public static void ProcessList<T>(List<T> childList)
    {
    }

}

Upvotes: 2

Related Questions