Search code examples
asp.netasp.net-core.net-corerazor-pages

Get page URL from markup in Razor Pages


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?


Solution

  • 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"