Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Route Values in Razor Pages

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
like image 853
Ertan Hasani Avatar asked May 06 '18 18:05

Ertan Hasani


1 Answers

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="")).

like image 158
Bodacious Avatar answered Sep 21 '22 10:09

Bodacious