I want to redirect to an action in the same controller, but lose the route values (in particular, the id
value). This is turning out to be surprisingly difficult. I have routes configured like this:
context.MapRoute(
"Monitoring_controllerIdSpecified",
"Monitoring/{controller}/{id}/{action}",
new { action = "Status" }
);
context.MapRoute(
"Monitoring_default",
"Monitoring/{controller}/{action}",
new { controller = "Events", action = "Index" }
);
... and an action method inside EventsController
something like this:
public ActionResult Status(int id) {
if (id > 1000) {
TempData["ErrorMessage"] = "ID too high.";
return RedirectToAction("Index", new { id = (int?)null });
}
// (code to display status)
}
If I then access something like /Monitoring/Events/1001
, the RedirectToAction
is indeed invoked, but I get redirected to /Monitoring?id=1001
instead of just /Monitoring
. It seems to be matching the first route, Monitoring_controllerIdSpecified
, even though that route has id
as a mandatory route parameter and I told it to set id
to null, and bizarrely turning id
into a query string key. In other words, it is not properly clearing/removing the id
route value. Setting id
to an empty string in the routeValues
object passed to RedirectToAction
just gives the same effect as setting it to null
.
Why is it doing this and how can I convince it not to match the first route because id
has been completely removed from the route values?
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.
The RedirectToAction() Method This 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.
Finally, the PersonModel class object is passed to the RedirectToAction method along with the name of the destination Controller and its Action method. The Controller consists of the following Action method. Inside this Action method, the PersonModel class object is received.
RedirectToAction(String, String, RouteValueDictionary) Redirects to the specified action using the action name, controller name, and route values.
Thanks to @Slicksim I found that the answer is to remove the key from RouteData.Values
rather than setting it to null:
public ActionResult Status(int id) {
if (id > 1000) {
TempData["ErrorMessage"] = "ID too high.";
RouteData.Values.Remove("id");
return RedirectToAction("Index");
}
// (code to display status)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With