Get Route Values in Razor Pages
Asked Answered
C

1

8

I want to know how can I get the route values in Razor Pages (Page.cshtml). Ex. https://localhost:44320/AdminPanel/Admins if I was using MVC i would get these datas as

var controller = ViewContext.RouteData.Values["Controller"]; //AdminPanel
var action = ViewContext.RouteData.Values["Action"]; //Admins

How can i get these values in Razor Pages?

For anyone trying to get it you can get it by:

var fullRoute = ViewContext.RouteData.Values["Page"]; // AdminPanel/Admin
Cupric answered 6/5, 2018 at 18:0 Comment(2)
You do not have a controller in the razor pages. What specifically are you trying to get ?Postmeridian
@Postmeridian I am trying to get that value Admins or the full route AdminPanel/Admins in page. I tried it and i found that i could get that AdminPanel/Admins by ViewContext.RouteData.Values["Page"];Cupric
F
6

Assuming you have a page named AdminPanel.cshtml in your Pages folder, add a parameter after @page on the first line, like this:

@page "{action}"

Then in the code behind (AdminPanel.cshtml.cs), add a prop and a parameter to your OnGet method like so:

private string _action;

public void OnGet(string action) {
  _action = action; //now do whatever you want with it
}

You can add a getter if you want to access it in your model back on the cshtml page.

Note: doing the above will make that page require an action be specified. Alternatively, you can also make it optional by adding a question mark (@page "{action?}") and setting a default value in your OnGet (OnGet(string action="")).

Forestforestage answered 20/7, 2018 at 13:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.