Liquid Core
Liquid Core

Reputation: 1

ASP NET MVC 5: Any way to avoid/ intercept back browser button?

Does a real solution exist to the problem of being able to go back and forth with browser buttons in a ASP.NET MVC 5 application?

Use case:

Page A: Displays some data in a table and 2 buttons "Delete, Confirm". First one deletes data, second one goes to page B Page B: Displays some other data based on the previous, and a "Continue with next step" button.

Pages actions are in GET. Buttons are in POST (with a form)

User clicks "Delete", data gets deleted, then hits back browser button and Asp net mvc shows page A again. You still see data in the table and clicking "Delete" leads to an error. You can also click forward and go to the page B, which will still shows data even if the real data was deleted.

What happens as of now (Latest Chrome, Edge, didn't try other browsers): Seems browser automatically caches these pages. Hitting back and forth retrieves the cached version with data still in it (all cached). No action is called on the controller, you can go back and forth all you want and not a single call to the controller is made. So you don't have any real control over it.

Tests done: Back button doesn't cause postback to a controller action in MVC

Does nothing. Still retrieves the cached page.

How do we control web page caching, across all browsers?

Same as above.

https://forums.asp.net/t/1957310.aspx?Capture+Browser+Back+Button+and+execute+controller+action+

Same as above.

How to disable the browser back button in my mvc from only my login page?

Does not disable back button.

And so on with the various flavours of the previous links. I even tried mixing them togheter, putting all the headers and NoCache and such attributes and javascript togheter.

Nothing.

Solution found: Put the control on buttons, which calls an ajax post and are forced to do a real call everytime.

Does a solution for this exists?

Upvotes: 1

Views: 3110

Answers (4)

NMeneses
NMeneses

Reputation: 172

Place this script on the page you want to prevent the user getting back to: <script> this.history.forward(-1); </script>

Upvotes: 0

jjxtra
jjxtra

Reputation: 21160

Typically you would do a post and then redirect which solves the back button issue. More details here: https://damienbod.com/2018/06/15/asp-net-core-mvc-form-requests-and-the-browser-back-button/

Upvotes: 0

Arpit Srivastava
Arpit Srivastava

Reputation: 9

After deleting the record you can try this.

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now);
Response.Cache.SetNoServerCaching();
Response.Cache.SetNoStore();

Upvotes: -1

Adlorem
Adlorem

Reputation: 1517

Trying to override native web browser function is bad idea. You will struggle through multiple browsers behaviors and their further updates. The best solution is to reload your data on page entry through ex. ajax call using javascript.

Upvotes: 1

Related Questions