Redirect to Another Page with JavaScript in ASP.NET

In web development, there are occasions when we want to redirect the browser to another page without any interaction from the user. For instance, we might want to display the current page for 5 seconds and then automatically redirect to another page.

This could be done with the Refresh meta tag. But what if we want to start the count only after the user does something, like clicking on a button? Or maybe we need to validate the page before redirecting to another page.

With JavaScript, we can easily redirect to another page by setting the href property of the location object to another URL.

<script type="text/javascript">
            function redirect() {
                location.href = "";
        <asp:LinkButton ID="LinkButton1" runat="server" OnClientClick="redirect(); return false;">Go to Blog</asp:LinkButton>

If we’re redirecting the user to another page in the same project, we can use the Page.ResolveUrl() function on the server to get the correct URL, no matter where we’re calling this from. This is useful when our code is in a user control.

location.href = '<%= Page.ResolveUrl("~/About.aspx") %>';

This will render the following when we run the application.

location.href = '/About.aspx';

We can even use location.href to reload the current page.

Please leave your comments if you have any question.

Get Free Updates
Related Posts