Redirect to previous page on Button Click using C# and VB.Net in ASP.Net

Last Reply 14 days ago By dharmendr

Posted 14 days ago

hello,

 

i want to add back button in asp dot net app, so user can just click on go on previous pages they browse if there is not previous page button is disabled.

 

please advice

Posted 14 days ago

Hi nauna,

There are two ways of do this.

1. By setting PostBackUrl property of ASP.Net Button, LinkButton and ImageButton.

2. By using Server.Transfer.

Check this example. Now please take its reference and correct your code.

CS.aspx

<asp:Button ID="btnResponseRedirect" Text="Response Redirect" runat="server" />
<asp:Button ID="btnServerTransfer" Text="Server Transfer" runat="server" OnClick="ServerTransfer" />

CS.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    btnResponseRedirect.PostBackUrl = "Default.aspx";
}

protected void ServerTransfer(object sender, EventArgs e)
{
    Server.Transfer("Default.aspx");
}

CS.aspx.vb

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    btnResponseRedirect.PostBackUrl = "Default.aspx"
End Sub

Protected Sub ServerTransfer(ByVal sender As Object, ByVal e As EventArgs)
    Server.Transfer("Default.aspx")
End Sub

Then you can check with PreviousPage property.

Default.aspx

<asp:Button ID="btnResponseRedirect" Text="Go To Previous Page Response Redirect"
    runat="server" Enabled="false" />
<asp:Button ID="btnServerTransfer" Text="Go To Previous Page Server Transfer" runat="server"
    Enabled="false" />

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (PreviousPage != null)
        {
            btnServerTransfer.Attributes.Add("onClick", "javascript:history.back(); return false;");
            btnServerTransfer.Enabled = true;
            btnResponseRedirect.Attributes.Add("onClick", "javascript:history.back(); return false;");
            btnResponseRedirect.Enabled = true;
        }
    }
}

Default.aspx.vb

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        If PreviousPage IsNot Nothing Then
            btnServerTransfer.Attributes.Add("onClick", "javascript:history.back(); return false;")
            btnServerTransfer.Enabled = True
            btnResponseRedirect.Attributes.Add("onClick", "javascript:history.back(); return false;")
            btnResponseRedirect.Enabled = True
        End If
    End If
End Sub

Screenshot