Redirect to the Caller Action in ASP.NET MVC3

1.8k views Asked by At

Assume we have an action like:

public ActionResult Display(long Id){

  //Do something

return RedirectToAction(//To the Caller)

}

So Display action called by some Views, like:

Index View : @Html.ActionLink("Show", "Display", new { [email protected] } )

So I need in Display: return RedirectToAction("Index")

Or

Edit View : @Html.ActionLink("Show", "Display", new { [email protected] } )

I need in Display: return RedirectToAction("Edit")

and so on.

How can we find which action call Display and in the end of the action returned to the caller action? what is your suggestion?

3

There are 3 answers

0
Shyju On BEST ANSWER

How about passing one more parameter along with id in the ActionLink method?

@Html.ActionLink("Show", "Display", new { [email protected] ,from="Edit"} )

and

@Html.ActionLink("Show", "Display", new { [email protected] ,from="Index"} )

and in your action method, accept that as well

public ActionResult Display(long Id,string from)
{

  //Not 100 % sure what you want to do with the from variable value.
   return RedirectToAction(from);
}
0
danludwig On

If you don't want to pass a variable to the redirecting action method, you could also check the Request.UrlReferrer and use that instead.

public ActionResult Display(long Id){

    var caller = Request.UrlReferrer != null 
        ? Request.UrlReferrer : "DefaultRedirect";

    // do something

    return Redirect(caller);
}
0
Fabio Milheiro On

You could use a returnUrl parameter.

On the caller:

@Html.ActionLink("Show", "Display", new { returnUrl = this.Url.PathAndQuery })

and your Display action all you have to do is redirecting to the returnUrl:

this.Redirect(returnUrl);

This is flexible enough for any other case you might have in the future.