Reputation: 2254
I'm trying to retrieve the page's URI parameters from within a child component.
Scenario: My Layout hosts a Navigation menu. Inside the links of these items I need to know parts of the URL but the URL is linked to the Page which in rendered through the Layout.
So the question becomes: Is there a way to get the page's url paramters in a child component without that child component having something like a @page
attribute?
What I've tried (but not limited to):
All these solutions work based on custom interpretation/parsing of the URI. I feel like I've already done that in the page component and should not have to create my own parser of the URI:
@page "/project/{name}"
<h3>Details </h3>
@code {
[Parameter] public string name { get; set; } = default!;
}
This page does not know about the NavComponent, the NavComponent is hosted through the Layout and as such I cannot pass the parameter as an attribute to the NavComponent:
<MenuItem Title="Home" Icon="fa fa-home" Url="/@name/fun-page"/> <-- name as retrieved in the page
<div>@technicalName</div>
@code {
[Parameter] public string name { get; set; } <-- get from page hosting this component
}
To restrict the answer:
NavigationManager
) but that's not pretty.Upvotes: 3
Views: 1880
Reputation: 45596
Suppose you've created a Company parent component which can get a route parameter to represent a company ID, the value of which is used to retrieve the company's details that may be displayed in a child component. You may define the parent component like this:
@page "/company"
@page "/company/{ID}"
@code {
[Parameter]
public string ID { get; set; }
}
Add this code to the MainLayout component
@code{
public string ID { get; set; }
protected override void OnParametersSet()
{
// pull out the "ID" parameter from the route data
object id = null;
if ((this.Body.Target as RouteView)?.RouteData.RouteValues?.TryGetValue("ID", out id) == true)
{
ID = id?.ToString();
}
}
}
Note: The code above extricates the value of the ID parameter from the RouteData, and stores it in the ID property. Now you can do with it, whatever you want... including passing it to the the NavMenu Component if it's necessary there. This is how you can do it:
Add a Component Parameter property to the NavMenu Component, like this:
[Parameter]
public string ID { get; set; }
And add an ID component parameter attribute to the NavMenu component instance (located at the top of the MainLayout component. It should be now <NavMenu ID="@ID"/>
Upvotes: 2
Reputation: 30016
Why not just cascade the values?
@page "/project/{name}"
<CascadingValue Name="ProjectName" Value="@name">
<h3>Details </h3>
<ProjectName/>
</CascadingValue>
@code {
[Parameter] public string name { get; set; } = string.Empty;
}
ProjectName.razor
<h3>@ProjName</h3>
@code {
[CascadingParameter(Name ="ProjectName") ] public string? ProjName { get; set; }
}
Upvotes: 3