PontiacGTX
PontiacGTX

Reputation: 355

Unable to cast object of type 'System.String' to type 'System.Int32'. on Blazor/Razor routing parameters

I have tried to call a page with /somepage/{Id} where Id is a [Parameter] with a int property and the route is called as a string, it shouldn't be impicitly converting string to int? why it it wouldnt work at all? I am expecting it would recognize the parameter as it is...

what should I try to have the routing middleware to recognize the parameter ? even in MVC this works just fine...

the page routing

@page "/EditEmployee/{Id}"

the link

<a href="/EditEmployee/@Employee.EmployeeId" class="btn btn-primary m-1">Edit</a>

the parameter in the page

    [Parameter]
    public int Id { get; set; }

the result is an exception and the page doesnt load

Upvotes: 3

Views: 3227

Answers (2)

Akram Al-Qaifi
Akram Al-Qaifi

Reputation: 650

Use: {Id:int}

@page "/EditEmployee/{Id:int}"

Full code:

@page "/EditEmployee/{Id:int}"

<a href="/EditEmployee/@Employee.EmployeeId" class="btn btn-primary m-1">Edit</a>

@code {
    [Parameter] public int Id { get; set; }
}

In this example the Id segment is an integer (int) type.


The route constraints shown in the following table are available.

Constraint Example Example Matches Invariant
culture
matching
bool {active:bool} trueFALSE No
datetime {dob:datetime} 2016-12-312016-12-31 7:32pm Yes
decimal {price:decimal} 49.99-1,000.01 Yes
double {weight:double} 1.234-1,001.01e8 Yes
float {weight:float} 1.234-1,001.01e8 Yes
guid {id:guid} CD2C1638-1638-72D5-1638-DEADBEEF1638{CD2C1638-1638-72D5-1638-DEADBEEF1638} No
int {id:int} 123456789-123456789 Yes
long {ticks:long} 123456789-123456789 Yes

warning

Route constraints that verify the URL and are converted to a CLR type (such as int or DateTime) always use the invariant culture. These constraints assume that the URL is non-localizable.


For more information see: ASP.NET Core Blazor routing and navigation


Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273244

Make it

 @page "/EditEmployee/{Id:int}"

Upvotes: 8

Related Questions