SRA
SRA

Reputation: 1691

How to navigate to previously visited page on 'ESC' key press. Asp.net mvc(c#)

How can I navigate to the last visited page when 'ESC' key is pressed. How can I do this using Asp.net mvc (c#). Please help

Upvotes: 1

Views: 2487

Answers (4)

Billy Buerger
Billy Buerger

Reputation: 81

I found this question 'cuz I was having a similar problem. rockinthesixstring's example works fine in IE but not in Firefox. alert() works fine even in Firefox, but not history.back(). In fact, I put the alert() after the history.back() and I got my alert but not my history. The same code worked fine on enter or any other key. In firefox, it appears that if you try to do some things when the escape key is pressed, it continues processing the escape key which then cancels whatever you were trying to do. Finally figured out that I had to force the propagation of the event to stop as shown below...

// Check for escape key
if (keyCode == 27)
{
    // Go back in our history
    history.back();

    if (window.event)
    {
        // IE works fine anyways so this isn't really needed
        e.cancelBubble = true;
        e.returnValue = false;
    }
    else if (e.stopPropagation)
    {
        // In firefox, this is what keeps the escape key from canceling the history.back()
        e.stopPropagation();
        e.preventDefault();
    }

    return (false);
}

Upvotes: 0

Chase Florell
Chase Florell

Reputation: 47417

The escape key doesn't cause any kind of postback, so you won't be able to do it with .net exclusively. What you'll need to do is capture the escape keypress with Javascript.

document.onkeydown = function(e){ 
          if (e == null) { // ie 
            keycode = event.keyCode; 
          } else { // mozilla 
            keycode = e.which; 
          } 
          if(keycode == 27){ // escape, close box, esc 
              // Go back one page
              history.back()
          } 
        };

Upvotes: 6

Xodarap
Xodarap

Reputation: 11849

You would need to do this in JavaScript, using history.back().

Upvotes: 0

rcravens
rcravens

Reputation: 8388

I think you can do this with a bit of JavaScript. The following link will navigate back in the history using the JavaScript history object.

<a href="javascript:history.go(-1)">Go back</a>

Attach a key press event to the document to monitor for the esc key and then use the history object.

Bob

Upvotes: 1

Related Questions