Share via

Go to the top of the page in Razor

Anjali Agarwal 1,591 Reputation points
2023-12-14T06:28:38.8966667+00:00

I have a Razor page that has table and other controls. I want to provide a link at the end of the page that says "Go to the Top of the Page". If user clicks on that link. The page should go all the way up. How can I achieve this on razor page.

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

Answer accepted by question author
  1. Bruce (SqlWork.com) 83,581 Reputation points Volunteer Moderator
    2023-12-15T20:35:29.16+00:00

    the browser has this feature built in, no js required.

    add a name to the body:

    <body name="top">

    then add a link(s) where you want:

    <a href="#top">Top</a>

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2023-12-14T08:31:25.5+00:00

    Hi @Anjali Agarwal,

    According to your description, I suggest you could consider using the javascript to achieve your requirement.

    You could put a tag at the end of page like below:

    <a id="goToTopLink" asp-page="yourrazorpagepath">Go to Top of the page</a>
    

    and add below js:

    @section Scripts {
        <script>
        
            document.addEventListener("DOMContentLoaded", function () {
                var goToTopLink = document.getElementById("goToTopLink");
                goToTopLink.addEventListener("click", function (e) {
                    e.preventDefault();
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                });
            });
        </script>
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.