Search code examples
javascriptasp.net-mvcback-buttonpage-refresh

Redirecting to a specific action on browser back button click MVC


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 :)


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>