MVC Return URL Suggestion

31 Views Asked by At

In MVC it is common to display some index view from which other actions are called, e.g. "Edit". In most cases a "Back" button is simple to code since we know where we want to go back to, i.e., the Index action.

However, there are scenarios where some "Edit" action may be called from a number of places. Now, we don't know where to go back to.

I've tried various ways of passing a returnUrl parameter to actions (e.g. HtmlHelpers that add the current RawUrl as a parameter to be processed at the called action) but they always seem to have some flaw. You end up needing to keep track of whether a call to an action was from Ajax for example.

Has anyone found a simple, workable solution? I've posted mine below

1

There are 1 best solutions below

0
AudioBubble On

I created an action attribute to adorn only certain actions such as "Index". This simply stores the current, rawUrl in session

public class ReturnableActionFilter : ActionFilterAttribute, IActionFilter
    {

    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {

            filterContext.HttpContext.Session["ReturnUrl"] = filterContext.RequestContext.HttpContext.Request.RawUrl;

            this.OnActionExecuting(filterContext);
}

In my breadcrumb partial view I look for the return URL in session and check if it is the current action. If not, a return URL is displayed (We don't return to the action we are already on).

string returnUrl = null;

var controllerName = ViewContext.RouteData.GetRequiredString("controller");
var actionName = ViewContext.RouteData.GetRequiredString("action");

// we don't return to the same controller/action we are in
if (Session["ReturnUrl"] is string r)
{
    if (!r.StartsWith("/" + controllerName + "/" + actionName))
    {
        returnUrl = r;
    }
}

The return link

@if (returnUrl != null)
{
    <li class="breadcrumb-item" title="Back"><a href="@(returnUrl)">&larr;Back</a></li>
}

Within an action I can also look up the session value and return after performing an edit for example.