GauLP
GauLP

Reputation: 25

back button functionality in MVC application

I have a requirement to implement Back button functionality in MY MVC2 application(with explicit Back buttons in the application, not via browser back button).

I have gone through the link here Back button functionality using ASP.net MVC which advises to use Request.UrlReferrer. and it works well whenever I have a HTTP Get (as it comes up with querystring.) but I face issue when previous page was a HTTP POST with no querystring.

Has anyone worked on a solution like this?

We have initial thoughts of generating and storing links like Stack, and popping out urls one by one when user clicks on 'Back' button. But if there is a better solution\design pattern which helps me achieve that?

Upvotes: 2

Views: 10330

Answers (1)

Tomi Lammi
Tomi Lammi

Reputation: 2126

You could store the returnurl to actionresult routevalues and have a html helper for back link.

Helper:

public static class HtmlHelpersExtensions
{
    public static MvcHtmlString BackLink(this HtmlHelper helper,string defaultAction)
    {
        string returnUrl = HttpContext.Current.Request["returnUrl"];
        // If there's return url param redirect to there
        if (!String.IsNullOrEmpty(returnUrl))
        {
            return new MvcHtmlString("<a href=" + returnUrl + " >Back</a>");
        }
        // if user just posted and there's no returnurl, redirect us to default
        else if (HttpContext.Current.Request.HttpMethod == "POST")
        {
            return helper.ActionLink("Back", defaultAction);
        }
        // we didn't post anything so we can safely go back to previous url
        return new MvcHtmlString("<a href=" + HttpContext.Current.Request.UrlReferrer.ToString() + " >Back</a>");
    }
}

Controller:

    public ActionResult MyAction(string returnUrl)
    {
        return View(new MyModel());
    }
    [HttpPost]
    public ActionResult MyAction(MyModel mm, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            // No returnurl, redirect us to somewhere
            if (string.IsNullOrEmpty(returnUrl))
                return RedirectToAction("Index");

            // redirect back
            return Redirect(returnUrl);
        }

        return View(mm);
    }

Usage:

@Html.ActionLink("MyAction", "MyAction", new { returnUrl = Request.RawUrl.ToString() })

Backlink in MyAction.cshtml

@Html.BackLink("Index")

Now the helper decides whether it uses returnUrl param, default action or takes you back via urlreferrer.

Upvotes: 4

Related Questions