RedirectToAction and RedirectToRoute
58,852
Omit parameter defaults to make parameters required:
routes.MapRoute(
"CreateAdditionalPreviousNames", // Route name
"Users/{controller}/{action}/{userId}/{applicantId}", // URL with parameters
new { controller = "UsersAdditionalPreviousNames", action = "Index" }
);
For route redirect, try this:
return RedirectToRoute(new
{
controller = "UsersAdditionalPreviousNames",
action = "Index",
userId = user.Id,
applicantId = applicant.Id
});
Another habit I picked up from Steve Sanderson is not naming your routes. Each route can have a null name, which makes you specify all parameters explicitly:
routes.MapRoute(
null, // Route name
"Users/{controller}/{action}/{userId}/{applicantId}", // URL with parameters
new { controller = "UsersAdditionalPreviousNames", action = "Index" }
);
Related videos on Youtube
Author by
user1079925
Updated on August 19, 2020Comments
-
user1079925 almost 4 years
In my controller of webpage 1, I want to redirect to Webpage 2, passing 2 variables.
I tried using RedirectToRoute, but cannot get it to work; wrong URL is displayed. I then switched to using RedirectToAction.
my code:
Routing
routes.MapRoute( "CreateAdditionalPreviousNames", // Route name "Users/{controller}/{action}/{userId}/{applicantId}", // URL with parameters new { controller = "UsersAdditionalPreviousNames", action = "Index", userId = UrlParameter.Optional, applicantId = UrlParameter.Optional } // Parameter defaults );
RedirectToAction (which works)
return RedirectToAction("Index", "UsersAdditionalPreviousNames", new { userId = user.Id, applicantId = applicant.Id });
RedirectToRoute (doesn't work)
return RedirectToRoute("CreateAdditionalPreviousNames", new { userId = user.Id, applicantId = applicant.Id });
Oh, and one other thing, can you make parameters required, rather than optional....if so, how?
-
Erik Funkenbusch over 12 yearsWhat do you expect to happen if they don't supply the parameters? Yes, it's possible, but all that will happen is a 404 error will occur, or something similar. Is that what you want?
-
-
user1079925 over 12 yearsThanks olivehour - that worked great. Just wondered why my version of RedirectToRoute doesn't work as I'm following the signature of the overloaded method....any ideas? Thanks
-
danludwig over 12 years@user1079925, like I said, I picked up the habit of not naming my routes, so I never use the overload that takes a route name. Hopefully someone else will answer who can tell you what went wrong there. This could be one of the reasons to not name your routes, the habit has paid off for me.
-
user1079925 over 12 yearsOk....I'm going to take your lead and move away from route naming - seemds like its a hinderance rather a help.
-
Lijin Durairaj over 7 yearsthis doesnt answer the solution of the problem described in the question, how can this be marked as an accepted answer then