3
votes

In MVC, I think we used @Html.Url() to get the URL of a page from the markup. In Razor Pages, this no longer appears to be available.

Razor Pages has some great tag helpers that help create page links. But what if you want a page URL, such as from JavaScript? Does Razor Pages have any tools for getting the URL string?

2

2 Answers

4
votes

This will bring the current page url:

@Url.RouteUrl(ViewContext.RouteData.Values);

[UPDATE]

The above implementation will return current page url without QueryString values e.g. /Users/Index

To include QueryString values after ? use below implementation:

@{
    var routeUrl = Url.RouteUrl(ViewContext.RouteData.Values);
    var qsPath = ViewContext.HttpContext.Request.QueryString.Value;
    var returnUrl = $"{routeUrl}{qsPath}";
}

The end result will include route and query string values:

// returnUrl = "/Users/Index?p=1&s=5"
0
votes

Some additional info to the above answer. If you are looking for parsed value of the components of the query string you can use the "Query" member of Request object and pass in the name of the query parameter e.g.

var returnUrl = ViewContext.HttpContext.Request.Query["returnUrl"].ToString();

If you have passed a parameter by the name "returnUrl" in the query string its value is returned. If it does not exist you will get an empty string.

I found this very helpful. I know this was not the EXACT question asked but thought I would share this information which maybe helpful to someone inexperienced like myself.