Return the previous page with the back button

Asked

Viewed 9,298 times

3

I have a back button that is supposed to return to the previous page, regardless of which page is on the system. How can I do this using MVC 4? The returnURL has something to do with this feature?

  • 3

    Depends ... this can be the window.history.back() that you want to implement with JAVASCRIPT, this is independent factor of technology.

3 answers

6


You can do the following:

@Html.ActionLink("Voltar", "ActionDeVoltar", "ControllerQualquer", new { returnUrl = this.Request.UrlReferrer }, null)

Put in your Controller common a Action thus:

public ActionResult ActionDeVoltar(string returnUrl)
{
    if (returnUrl != "") return Redirect(returnUrl);
}

It’s not as elegant as Javascript, but at least it generates static HTML.

  • I’m trying to use javascript, the problem is that when I use it on the page, it gives a refresh. But when I open the Chrome console and type in the code, it works...

  • The above code is also updating the page only...

  • Sorry. Wrong variable. Check now.

  • Now yes! Mass... why should I return only if the returnUrl == "" ?

  • It was bad. It’s sleep. I’ve corrected.

3

<a href="@Request.UrlReferrer" class="btn btn-default">Voltar</a>

0

How about doing your custom HtmlHelper however you wish?

Well, for that, create a class of Extensions to create our Helper. In case you don’t know what I’m talking about, this link has a brief explanation of what it is and how to develop a Custocustom HtmlHelper.

For example and I called mine HtmlExtensions, and she was like this:

public static class HtmlExtensions
    {
        public static MvcHtmlString ReturnActionLink(this HtmlHelper htmlHelper,string linkText, IDictionary<string, object> htmlAttributes = null)
        {
            var url = htmlHelper.ViewContext.HttpContext.Request.UrlReferrer.ToString();

            var link = htmlHelper.ActionLink(linkText,null, htmlAttributes);

            string replacedString = Regex.Replace(link.ToString(), "href=\"([^ \"]*)", "href=\"" + url);

            return new MvcHtmlString(replacedString);
        }
    }

And in his View, just call the custom Helper.

@Html.ReturnActionLink("voltar")

In this Helper I simply create a Html.ActionLink normal and replace the value with UrlReferrer shown in previous responses.

With this you can do whatever you want, customize class, tag, etc. Even if you want to use the window.history.back() in a onclick() it is possible.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.