如何使用RedirectToAction重定向到不同控制器的默认操作?

发布于 2024-10-20 21:05:43 字数 866 浏览 2 评论 0原文

我正在尝试使用以下代码从 http://mywebsite/Home/ 执行 RedirectToAction:

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

上面的代码将成功带我到

http://mywebsite/Profile/Index/223224

我需要做什么才能做到重定向到

http://mywebsite/Profile/223224

谢谢。

我想出了如何做到这一点。

首先我必须添加自定义路由规则:

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

然后我可以执行以下操作:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

大姐,你呐 2024-10-27 21:05:45

我刚刚偶然发现了完全相同的问题。通过使用路由名称重定向解决了这个问题:

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

所有变量都会被记住,所以如果你有像/{x}/{y}/Profile/{action}/{id}这样的Url,你只需要清除像我一样行动。

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.

小镇女孩 2024-10-27 21:05:45

假设您的 / 控制器被命名为“Home”

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

,嗯,我想这仍然是 /Index/num...我不确定您是否可以在没有自定义路由的情况下省略 Index 位。

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.

手长情犹 2024-10-27 21:05:44

我认为你可以这样做:

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

I think you can do:

return RedirectToAction("","Profile", new { id = formValues["id"] });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文