Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you redirect to the calling page in ASP.NET MVC?

Let's say I have a controller action that deletes an item out of a user's shopping basket. This controller action is triggered by performing a POST to the url ~/delete/{id}. If I have several pages on my application that will post to this url, how do I construct the controller action to redirect back to the page that posted to it?

like image 605
Kevin Pang Avatar asked Jan 30 '09 10:01

Kevin Pang


People also ask

How do I redirect to an action in ASP NET MVC?

RedirectToAction(String, String, RouteValueDictionary) Redirects to the specified action using the action name, controller name, and route values.

How can I link a page to another page in ASP NET MVC?

Adding View to Controller in Asp.Net MVC Here is Project view after adding all View related to Action Method in MainController. Now on Index view, let's add Hyperlink. To add Hyperlink, we need to begin with @html helper with following Action Link, then we need to provide linkText to display and ActionName.


1 Answers

You should provide a RedirectToUrl parameter from the posting page.

Relying on referrer headers is not a good practice.

Instead, do something like this:

public ActionResult Delete(int id, string RedirectToUrl)
{
  // check if RedirectToUrl is null or empty and redirect accordingly
}

On the posting view or partial view you can provide the parameter in several ways:

<%= Html.Hidden("RedirecToUrl","/my/lovely/url") %>

or

<form action="/item/delete/22?RedirectToUrl=/my/lovely/url">

I'd prefer the first option.

like image 91
Christian Dalager Avatar answered Sep 28 '22 03:09

Christian Dalager