atbebtg
atbebtg

Reputation: 4083

How to use RedirectToAction to redirect to the default action of different controller?

I am trying to do a RedirectToAction from http://mywebsite/Home/ using the following code:

return RedirectToAction("Index","Profile", new { id = formValues["id"] });

The above code will succesfully take me to

http://mywebsite/Profile/Index/223224

What do I have to do to make it redirect to

http://mywebsite/Profile/223224

Thank you.

I figured out how to do this.

First I have to add custom route rule:

routes.MapRoute("Profile", "Profile/{id}", new { controller = "Profile", action = "Index", id = UrlParameter.Optional });

Then I can do the following:

[AcceptVerbs(HttpVerbs.Post)]
public RedirectResult Index(FormCollection formValues)
{
   return Redirect("~/Survey/" + formValues["Id"]);
}

Upvotes: 1

Views: 4388

Answers (3)

Marko Kovačić
Marko Kovačić

Reputation: 67

I just stumbled upon exact same problem. Got it solved by redirecting using route name:

return RedirectToRoute("profile", new { action = "" });

all variables will be remembered so if you have Url like /{x}/{y}/Profile/{action}/{id} you just need to clear action as I did.

Upvotes: 1

asawyer
asawyer

Reputation: 17808

Assuming your / controller is named "Home"

Return RedirectToRoute(new {controller="Home",action="Index",id=formValues["id"]});

Hmm I suppose this would be still /Index/num though... I'm not sure if you can get away with leaving out the Index bit there without custom routing.

Upvotes: -1

John Bledsoe
John Bledsoe

Reputation: 17652

I think you can do:

return RedirectToAction("","Profile", new { id = formValues["id"] });

Upvotes: 1

Related Questions