Search code examples
javascriptasp.netback

A simple "back" button in ASP


This should be so simple, and indeed I have found many solutions on SO and elsewhere. But nothing I do seems to work. This is what I currently have:

<asp:ImageButton ID="BackButton" runat="server" ImageUrl="Images/redAbort.png"
    OnClientClick="backClick()" CssClass="TVMback-button" />

And:

function backClick(sender) {                                    
    history.back(1);
    return false;
}

But the page just refreshes. I get to this page using Javascript (via document.location), by the way. And I really do want to implement a "back" function here, rather than targeting a preset URL, as I could end up here from various sources. But even when I do try to set document.location to the URL of the previous page, nothing happens.

So I guess I've missed something stupid simple.

I have tried a bazillion of combinations though. Including prefacing history with document. and window., as well as trying .go(-1), etc.

I have also tried returning false, true, nothing at all. I have tried to return Santa Claus and the shoes I bought for my girlfriend in Raleigh, NC back in 2012, as they were a size too big. But nothing seems to work.


Solution

  • You are not propagating the value returned by backClick() from the event handler.

    You should write:

    <asp:ImageButton ID="BackButton" runat="server" ImageUrl="Images/redAbort.png"
        OnClientClick="return backClick();" CssClass="TVMback-button" />
    

    Also note that history.back() does not take an argument, so you only have to write:

    function backClick()
    {
        history.back();
        return false;
    }