Arnis Lapsa
Arnis Lapsa

Reputation: 47567

ASP.NET MVC how to implement link which returns to previous page?

Title said it all.

Some context:
I got a search mechanism - search view, search results view and a details view (which represents one item of results, like a formview in webforms). I want a link in details view, which would return user to search results view.

Ideas:
Just read about TempData, but i guess that wouldn't help, cause user might call some actions before he wants to return.

Session might work, but I'm not sure how exactly i should handle it.

I don't want to use javascript to accomplish this.

Edit:
Seems that i'll stick with eu-ge-ne`s solution. Here's result:

#region usages

using System.Web.Mvc;
using CompanyName.UI.UIApp.Infrastructure.Enums;

#endregion

namespace CompanyName.UI.UIApp.Infrastructure.Filters
{
    /// <summary>
    /// Apply on action method to store URL of request in session
    /// </summary>
    public class RememberUrlAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting  
           (ActionExecutingContext filterContext)
        {
            var httpContext = filterContext.HttpContext;

            if (httpContext.Request.RequestType == "GET"
                && !httpContext.Request.IsAjaxRequest())
            {
                SessionManager
                .Save(SessionKey.PreviousUrl,
                      SessionManager.Get(SessionKey.CurrentUrl) ??
                      httpContext.Request.Url);

                SessionManager
                .Save(SessionKey.CurrentUrl,
                      httpContext.Request.Url);
            }
        }
    }
}

Btw, how does .IsAjaxRequest() method works? It understands only MS AJAX or it's smarter than that?

Upvotes: 5

Views: 7287

Answers (3)

omoto
omoto

Reputation: 1220

<a href="javascript:go(-1)">Yo</a>

:)

Upvotes: -2

eu-ge-ne
eu-ge-ne

Reputation: 28153

I think you need something like this custom filter (not tested - have no VS at the moment):

public class PrevUrlAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var httpContext = filterContext.HttpContext;
        var session = filterContext.HttpContext.Session;

        if (httpContext.Request.RequestType == "GET"
            && !httpContext.Request.IsAjaxRequest())
        {
            session["PrevUrl"] = session["CurUrl"] ?? httpContext.Request.Url;
            session["CurUrl"] = httpContext.Request.Url;
        }
    }
}

Upvotes: 5

Adrian Godong
Adrian Godong

Reputation: 8911

You can examine the HTTP Referrer header to retrieve the previous URL.

Of course, you'll have to handle gracefully just in case the user does not pass in this value.

Upvotes: 1

Related Questions