Question

How can I redirect to a controller action when the browser's back button is clicked. I can achieve this by clicking my own button or link on the page hustle-free but getting the same result from clicking the browser's back or refresh button is an issue.

I have a controller called "Notifications"
An action in the contoller called "Unlock" whick takes "id" as an argument.

My Link works perfectly fine:

    @Html.ActionLink("Back to List", "Unlock", new { id = Model.NotificationId })

I've tried using javascript:

    <script>
        window.onbeforeunload = function () {
            window.location.replace("/Notifications/Unlock/" + "@Model.NotificationId");
            }
    </script>

even window.location.href doesn't seem to work. Please help. Thanks :)

Was it helpful?

Solution

This worked for me:

<script>
    window.onunload = function () {
        $.ajax({
            url: '/Notifications/Unlock/' + '@Model.NotificationId',
            type: 'POST',
            datatype: "json",
            contentType: "application/json; charset=utf-8"
        });
    };
</script>

OTHER TIPS

You can't do this. When the user presses the back button of the browser, a cached version of the previous page will be rendered and the server will never be called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top