arjun kr
arjun kr

Reputation: 973

How route parameter assigns the value to property in Blazor?

Below block of code is Blazor documentation. But I am not able to figure out how and on what basis 'text' route parameter assigns value to the Text property.

@page "/RouteParameter"
@page "/RouteParameter/{text}"

<h1>Blazor is @Text!</h1>

@code {
    [Parameter]
    public string Text { get; set; }

    protected override void OnInitialized()
    {
        Text = Text ?? "fantastic";
    }
}

Upvotes: 1

Views: 2730

Answers (2)

Adam Vincent
Adam Vincent

Reputation: 3811

There's more reading!

The Blazor documentation you were reading is not intended to explain ALL of routing. It only goes so far as to explain how Blazor uses ASP.NET Core Routing.

More on ASP.NET Core Routing


Tying in to ASP.NET Core Routing

In your Blazor Web App's Startup.cs file you'll see something like the following:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
    });

MapBlazorHub() is how Blazor ties into the ASP.NET Core Routing.


Blazor routing is using the same Router as MVC and Razor pages.

Example:

MVC -> [Route("customer/{id:int}")] (attribute on a controller)

Razor Pages -> @page "/customer/{id:int}" (page directive)

Blazor -> @page "/customer/{id:int}" (page directive)


Step by step

Example route: @page "/customer/{id:int}"

  • The route is navigated to by the end user
  • The URL is matched to an endpoint by the ASP.NET Core Router
  • The URL is tokenized into route values
  • The "{id:int}" are processed by Route Constraints, and accepted or rejected, and in this case, converted to a strongly typed int
  • The route values is packaged and given to your code (controller, component, etc), and it provides the customer id of 1 as a parameter.

Warning : this is high level and glossing over some key things, please continue reading More on ASP.NET Core Routing

Upvotes: 3

Vencovsky
Vencovsky

Reputation: 31585

TL;DR

Blazor matches route param with properties by ignoring the word's case.


Blazor gets all parameters from the route and all properties from your class and assigns it ignoring the case.

So the lower case text goes into Text.

This would also work

@page "/RouteParameter"
@page "/RouteParameter/{Text}" // upper case Text

<h1>Blazor is @Text!</h1>

@code {
    [Parameter]
    public string Text { get; set; }

    protected override void OnInitialized()
    {
        Text = Text ?? "fantastic";
    }
}

But because normally the url doesn't have upper case, and C# properties starts with upper case, they maybe this comparison ignoring case.

Upvotes: 2

Related Questions