Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
358 views
Welcome To Ask or Share your Answers For Others

1 Answer

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" }
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...