Cascading Values and Parameters

In Blazor, you can pass a value from a parent to a child component using component parameters. You will have to write all the wiring code from the parent to all the descendants to pass the value. Another more convenient way of doing this is by using cascading values and parameters. To do this, you simply specify a CascadingValue in the parent component for passing to the descendant components. In the descendant components, simply specify a CascadingParameter to retrieve the value.

For example, the following passes the string "Hello Title" (CascadingValue) to the descendant components, including those of @Body.

MainLayout.cshtml (Parent)


@inherits BlazorLayoutComponent

<CascadingValue Value="@TitleValue" Name="TitleValue">
<div class="content px-4">
        @Body
</div>
</CascadingValue>

@functions{
	string TitleValue="Hello Title";
}

To access TitleValue, simply specify the CascadingParameter attribute. By default, Cascading values can automatically bound to Cascading parameters by type. In our case, we specify a Name in our CascadingParemeter to clearly indicate the variable we want to bind to.

index.cshtml (Child)


<h3>@Title</h3>

@functions{
        [CascadingParameter (Name = "TitleValue")] protected string Title { get; set; }
}

If index.shtml uses a Blazor Component, we can also easily access TitleValue using a similar syntax.

GrandchildComponent.cshtml


<h3>@Title</h3>

@functions{
        [CascadingParameter (Name = "TitleValue")] protected string Title { get; set; }
}

Instead of passing (cascade) a single value, you can also pass a class object with multiple attributes as shown below:

Shapes/Rectangle.cs


namespace Shapes
{
    public class Rectangle
    {       
        public double Width { get; set; }
        public double Height { get; set; }
    }
}

MainLayout.cshtml (Parent)


@inherits BlazorLayoutComponent
@using Shapes

<CascadingValue Value="@rect" Name="ReactangleValue">
<div class="content px-4">
        @Body
</div>
</CascadingValue>

@functions{
	Rectangle rect= new Rectangle { Width=5.0,Height=5.0};
}

To use the attribute in the child component, you can do the following:

index.cshtml (Child)


<p>@rectParam.Width</p>

@functions{
        [CascadingParameter (Name = "RectangleValue")] 
        protected string rectParam { get; set; }
}