I have the following code in an MVC view that I'm using to test window.history.back()
If the user clicks the link (highlighted in red) within the paragraph tag, window.history.back() executes as I would expect. It takes me back to the prior page with state maintained on that page. However, if the user clicks the button, I don't get the same behavior. The current view is reloaded, or at least an attempt is made to reload the current page. But it fails. And it doesn't matter if the jQuery is executed, or I put the window.history.back() call within the Button onClick, the same thing happens.
A piece of information which might be helpful. The button is inside an HTML.BeginForm and the line in the paragraph tag is not.
Anyone know why this is happening?
I have the following code in an MVC view that I'm using to test window.history.back()
If the user clicks the link (highlighted in red) within the paragraph tag, window.history.back() executes as I would expect. It takes me back to the prior page with state maintained on that page. However, if the user clicks the button, I don't get the same behavior. The current view is reloaded, or at least an attempt is made to reload the current page. But it fails. And it doesn't matter if the jQuery is executed, or I put the window.history.back() call within the Button onClick, the same thing happens.
A piece of information which might be helpful. The button is inside an HTML.BeginForm and the line in the paragraph tag is not.
Anyone know why this is happening?
Share Improve this question asked Apr 1, 2013 at 19:34 Randy MinderRandy Minder 48.5k54 gold badges218 silver badges369 bronze badges 2-
2
add
type="button"
to ensure it isn't being interpreted as a submit button. – Kevin B Commented Apr 1, 2013 at 19:36 - @KevinB - That was it! Silly oversight on my part. If you create this as an answer, I'll accept it. – Randy Minder Commented Apr 1, 2013 at 19:42
2 Answers
Reset to default 8The browser is probably interpreting the button as a submit button and submitting the form, thus causing a page refresh. Adding type="button"
will prevent that.
<button type="button">Cancel</button>
$('#cancelButton').click(function(e){
e.preventDefault();
/* ... code ... */
});