Button.PostBackUrl + OnClick

Problem: Setting PostBackUrl stops the click event from firing. In other words, the server-side OnClick event is not fired before the URL of the web page (set by the PostBackUrl property) posts to when the button is clicked.

Scenario: FormA is going to run the code behind and take the user to FormB when clicking on the following button:

FormA.aspx:

<asp:Button ID="btnExample" runat="server" OnClick="btnExample_Click" Text="Spell Check" PostBackUrl="FormB.aspx" />

FormA.aspx.cs:

protected void btnExample_Click(object sender, EventArgs e)
{
  //run code...
}

Solution: Reference the PreviousPage on Page_Load.

In addition, you can set the PreviousPageType directive in the destination page which is a good practice and provides strong typing, but it is not necessary. I just added to the example for demonstration purposes.

FormB.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FormB.aspx.cs" Inherits="FormB" %>
<%@ PreviousPageType VirtualPath = "FormA.aspx" %>

FormB.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    if (PreviousPage != null) {  //this is necessary
        //run code...
    }
}

It’s important to reference PreviousPage, at least once, so it knows which page it’s from and can fire the event.

 

Advertisements

One thought on “Button.PostBackUrl + OnClick

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s