Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use RedirectToAction without passing query string parameters/route values

I have a "Thingy" controller for that looks like:

[HttpPost]
public ActionResult DeleteConfirmed(long? id) {
    // <Validate ID, delete associated records>
    return RedirectToAction("Index", "Thingy");
}

However, RedirectToAction keeps having its route values populated with the id from the parameters, whereas I want it to leave id as null so it redirects to www.mywebsite.com/Thingy instead of www.mywebsite.com/Thingy/1

In fact, I can visit www.mywebsite.com/Thingy directly and it works as expected.

I have tried:

RedirectToAction("Index", "Thingy")
RedirectToAction("Index", "Thingy", new { })
RedirectToAction("Index", "Thingy", new { id = (long?)null })

The last is particularly amusing because it redirects to www.mywebsite.com/Thingy?id=1 where as the others redirect to www.mywebsite.com/Thingy/1.

like image 233
Kaganar Avatar asked Oct 22 '14 21:10

Kaganar


People also ask

What is the difference between redirect () and RedirectToAction () in MVC?

RedirectToAction is meant for doing 302 redirects within your application and gives you an easier way to work with your route table. Redirect is meant for doing 302 redirects to everything else, specifically external URLs, but you can still redirect within your application, you just have to construct the URLs yourself.

How do I pass multiple parameters in RedirectToAction?

How do I pass multiple parameters in RedirectToAction? Second, to pass multiple parameters that the controller method expects, create a new instance of RouteValueDictionary and set the name/value pairs to pass to the method.

Which is correct syntax for RedirectToAction?

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

How do I use RedirectToAction?

The RedirectToAction() MethodThis method is used to redirect to specified action instead of rendering the HTML. In this case, the browser receives the redirect notification and make a new request for the specified action. This acts just like as Response. Redirect() in ASP.NET WebForm.


1 Answers

Add the following before your RedirectToAction() in your first example:

RouteData.Values.Remove("id");

I have a feeling the route values you specify are being merged with the original route values.

like image 189
Erik Philips Avatar answered Nov 05 '22 06:11

Erik Philips