Redirect to a URL on a button click in ASP.NET (JavaScript, jQuery or server-side)
"Go to page X when the user clicks this button" has several answers in Web Forms. If nothing needs to happen on the server first, the simplest is not a button at all but a link. When the server must work first, redirect from the click handler.
No server work needed: use a link
<asp:HyperLink runat="server" NavigateUrl="~/Orders/New.aspx" CssClass="button" Text="New order" />
A link navigates without script, can be opened in a new tab, and is announced correctly by screen readers. Style it as a button if the design requires.
Client-side redirect from a button
<asp:Button ID="btnHelp" runat="server" Text="Help"
OnClientClick="window.location.assign('Help.aspx'); return false;" />
return false cancels the postback that an asp:Button would otherwise trigger. Build the URL with ResolveUrl("~/Help.aspx") in code if the page may sit in a subfolder.
The same with jQuery, keeping script out of the markup:
$(function () {
$("#<%= btnHelp.ClientID %>").on("click", function (e) {
e.preventDefault();
var term = encodeURIComponent($("#<%= txtSearch.ClientID %>").val());
window.location.href = "Help.aspx?q=" + term;
});
});
location.href = … and location.assign(…) add a history entry; location.replace(…) does not, so the back button skips the current page. To open a new tab: window.open(url, "_blank", "noopener"), called directly in the click handler so popup blockers allow it.
Server-side redirect after work
protected void btnCheckout_Click(object sender, EventArgs e)
{
if (!IsValid) return;
int orderId = CreateOrder();
Response.Redirect("~/Orders/Confirm.aspx?id=" + orderId, false);
Context.ApplicationInstance.CompleteRequest();
}
Redirecting after a successful POST (Post/Redirect/Get) prevents the "resend form data?" prompt and duplicate orders on refresh. The false argument plus CompleteRequest() ends the request without the ThreadAbortException that Response.Redirect(url) uses internally.
Never redirect to a URL taken unchecked from user input (?returnUrl=…): check that it is local, for example with Uri.IsWellFormedUriString(url, UriKind.Relative) and a leading single slash, to avoid an open redirect.
Posting the form to another page
PostBackUrl sends the form itself to another page, which can read the values through PreviousPage: see Cross-page posting. A redirect after a countdown is in Redirect after a delay.
Which one to choose
| Need | Use |
|---|---|
| Plain navigation | HyperLink or <a href> |
| Navigation built from form values, no server work | Client-side location.href |
| Save first, then go elsewhere | Response.Redirect in the click handler |
| Send the whole form to another page | PostBackUrl |
| Page moved permanently | Response.RedirectPermanent (301) |
Official documentation
- Microsoft Learn: HttpResponse.Redirect, Button.PostBackUrl
- MDN: Location.assign(), Location.replace(), Window.open()
- OWASP: Unvalidated Redirects and Forwards Cheat Sheet