9

Please refer the following code blocks. For that code blocks, I have tried to access the parent component values into child component, but it always return the null value in child component.

<Parent TValue="TreeData">
 <Child TValue="TreeNode<TreeData>"></Child>
</Parent>

@code {
    public class TreeData
    {
        public string Value { get; set; }
    }
    public class TreeNode<TreeData>
    {
        public int Count { get; set; }
    }
}

**Parent Component:**

<CascadingValue Value="@this">
    @ChildContent
</CascadingValue>

**Child Component:** 

@code {
    [CascadingParameter]
    private Parent<TValue> ParentObj { get; set; }
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        //Parent obj always returns the null value
        ParentObj?.UpdateChildProperties("UpdateData", this);
    }    
}
SVB Ashok
  • 278
  • 1
  • 6
  • 1
    I'm struggling to piece together your code and create a working example. Can you restructure the code into the parent and child components? – MrC aka Shaun Curtis Aug 30 '21 at 16:34
  • why you create a generic class with specified class type? you have to use public parameter for cascade parameter. – mRizvandi Oct 17 '22 at 15:04

1 Answers1

0

Some general things to consider:

  1. Make sure your child component (or your _Imports.razor) has a using statement for that namespace.
  2. The [CascadingParameter] in the child must be public.
  3. Make the type of the [CascadingParameter] the name of the parent (without the.razor)
  4. If you have multiple different types you want to pass as a cascading parameter that's fine, just make another [CascadingParameter] in the child.
  5. If they need to use the same [CascadingParameter] in the child component then all those types that are being passed down must inherit from the same class (.razor). This .razor can be empty just make sure to include @inherits (whatever your base type is) and make the type of the [CascadingParameter] in the child the type of the base and in the on initialize you can check for type and cast it if needed.

I believe doing these things should fix this issue but as Curtis mentioned in the comment - it is difficult to follow this code with the way it is separated.

Kyle Cintron
  • 316
  • 2
  • 6