Return the previous page with the back button

3

I have a back button that supposedly should return to the previous page, regardless of which page on the system. How can I do this using MVC 4? Does returnURL have anything to do with this feature?

    
asked by anonymous 30.05.2014 / 16:21

3 answers

6

You can do the following:

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

Put a Controller like this in your% common%

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

It's not as elegant as JavaScript, but at least it generates static HTML.

    
30.05.2014 / 18:49
3
<a href="@Request.UrlReferrer" class="btn btn-default">Voltar</a>
    
05.08.2016 / 15:52
0

How about doing your custom HtmlHelper however you want?

Well, for this, create a Extensions class to create our Helper . If you do not know what I'm talking about, this link has a brief explanation of what is and how to develop a Custocustom HtmlHelper .

For the example, I called mine from HtmlExtensions , and it looks 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 its 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 answers.

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

    
05.08.2016 / 19:03