Blazor equivalent to @Url.Action or @Html.ActionLink

Viewed 803

In ASP.NET MVC, whenever you have a controller and an action in it, you could dynamically generate a link to it in a razor page like:

Url.Action("ProductController", "Index", new { id = "123" })

and this would return a string containing the path to that action with the specified route values:

/Product/123

Isn't there a similar method in Blazor where you could give it the component's name and route values:

Url.Component("ProductPage", new { id = "123" })

and get the path?

/Product/123
1 Answers

Check out NavigationManager: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.navigationmanager?view=aspnetcore-6.0. Inject that and you can do it. I am not sure if you can pass the route values as an object, though or if you'll need to make something like a NameValueCollection and use the Tostring() method on it.

In short, something like:

@inject NavigationManager NavManager;

// Markup here

@code {

    public void MyMethod() {
        var nameValueCollection = new NameValueCollection();
        var myUrl = "https://localhost:5000/somewhere/";
        // fill data
        NavManager.NavigateTo(myUrl + nameValueCollection.ToString(), false);
    }

}
Related