on html.actionlink click go to previous page

Cybercop picture Cybercop · Aug 27, 2013 · Viewed 59.6k times · Source

Currently in a link

Customer/businessunit/RepresentativeDetails?RepresentativeId=cd3a7263-78f7-41bd-9eb0-12b30bc1059a

I have following code for view

@Html.ActionLink("Back to List", "Index")

which takes me to this link

customer/businessunit/index

but rather that going to index page I want to go to previous page when the actionlink is clicked, which is

Customer/businessunit/BusinessUnitDetails/c4a86253-a287-441e-b83d-71fbb6a588bc

How do I create an actionlink that directs me to previous page? something like @Html.ActionLink("Back to Details", //go to previous page)

Answer

David picture David · Aug 27, 2013

Unless you're tracking what the previous page is on the server, why not just use the browser's internal history? In that case there wouldn't be a need for server-side code. You could just use something like this:

<a href="javascript:void(0);" onclick="history.go(-1);">Back to Details</a>

Or, separating the code from the markup:

<a href="javascript:void(0);" id="backLink">Back to Details</a>

<script type="text/javascript">
    $(document).on('click', '#backLink', function () {
        history.go(-1);
    });
</script>

This would send the user back to whatever was the last page in their browser history. (Of course, if they reached that page from any other source then it wouldn't take them "back to details" but instead just "back".)