Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 678
Arnis Lapsa Avatar asked Oct 15 '22 15:10

Arnis Lapsa


1 Answers

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;
        }
    }
}
like image 106
eu-ge-ne Avatar answered Oct 18 '22 22:10

eu-ge-ne