товіаѕ
товіаѕ

Reputation: 3264

C# ASP.NET Core Razor pages: How to access route constraint within markup

I have a Razor page with the markup starting like so:

@page {id:int?}
...

Now, if you access the page on a path /MyPage/5 the id parameter on the class method OnGet(Int32? id) will be set to the value 5.

I'd like to display some conditional markup depending on the value of the id, is there a way I can access the id in the markup directly?

I tried @id but it says it isn't defined - which makes sense I guess. I figured I could catch it in the OnGet(..) method and make it available through a property if there is no other way to do this directly. The downside to this approach is that I have to re-set the value every time a post-back happens.

Is there a way to do this?

Upvotes: 2

Views: 366

Answers (1)

Shaun Luttin
Shaun Luttin

Reputation: 141622

Short Answer

Here is one way to access the id value.

<p>RouteData.Values["id"]</p>

Debugging

If you want to debug you can dump all the available RouteData on the page like this:

<p>@Newtonsoft.Json.JsonConvert.SerializeObject(RouteData)</p>

The output will look something like this:

{"DataTokens":{},"Routers":[],"Values":{"page":"/Index","id":"101273123"}}

Upvotes: 3

Related Questions