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
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="")
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With