C# RedirectToAction 和 RedirectToRoute
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8944355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RedirectToAction and RedirectToRoute
提问by user1079925
In my controller of webpage 1, I want to redirect to Webpage 2, passing 2 variables.
在我的网页 1 控制器中,我想重定向到网页 2,传递 2 个变量。
I tried using RedirectToRoute, but cannot get it to work; wrong URL is displayed. I then switched to using RedirectToAction.
我尝试使用 RedirectToRoute,但无法让它工作;显示错误的网址。然后我切换到使用 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)
RedirectToAction(有效)
return RedirectToAction("Index", "UsersAdditionalPreviousNames", new { userId = user.Id, applicantId = applicant.Id });
RedirectToRoute (doesn't work)
RedirectToRoute(不起作用)
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?
哦,还有一件事,你能不能让参数成为必需的,而不是可选的……如果是这样,怎么做?
采纳答案by danludwig
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" }
);

