asp.net-mvc 从一个视图重定向到另一个视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14080515/
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
Redirect from a view to another view
提问by Nistor Alexandru
Hi I am trying to redirect from a view to a different view but I get a red squigly in visual studio.How can I redirect from inside a view to another view.This is what I have tryed but it does not work:
嗨,我正在尝试从一个视图重定向到另一个视图,但在 Visual Studio 中出现红色波浪线。如何从视图内部重定向到另一个视图。这是我尝试过的,但它不起作用:
@Response.Redirect("~/Account/LogIn?returnUrl=Products");
How can I redirect from my curent view to another view?
如何从当前视图重定向到另一个视图?
回答by NKCSS
It's because your statement does not produce output.
这是因为您的语句不会产生输出。
Besides all the warnings of Darin and lazy (they are right); the question still offerst something to learn.
除了达林和懒惰的所有警告(他们是对的);这个问题仍然提供了一些值得学习的东西。
If you want to execute methods that don't directly produce output, you do:
如果要执行不直接产生输出的方法,请执行以下操作:
@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}
This is also true for rendering partials like:
这也适用于渲染部分,如:
@{ Html.RenderPartial("_MyPartial"); }
回答by Darin Dimitrov
That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:
这不是 ASP.NET MVC 应该如何使用。您不会从视图重定向。您从相应的控制器操作重定向:
public ActionResult SomeAction()
{
...
return RedirectToAction("SomeAction", "SomeController");
}
Now since I see that in your example you are attempting to redirect to the LogOnaction, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize]attribute:
现在,因为我在您的示例中看到您正在尝试重定向到LogOn操作,所以您实际上不需要手动执行此重定向,而只需使用[Authorize]属性装饰需要身份验证的控制器操作:
[Authorize]
public ActionResult SomeProtectedAction()
{
...
}
Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl).
现在,当一些匿名用户尝试访问此控制器操作时,Forms 身份验证模块将在它命中该操作之前自动拦截该请求,并将用户重定向到您在 web.config ( loginUrl) 中指定的 LogOn 操作。
回答by Sergey Berezovskiy
Purpose of view is displaying model. You should use controller to redirect request before creating model and passing it to view. Use Controller.RedirectToActionmethod for this.
视图的目的是显示模型。在创建模型并将其传递给视图之前,您应该使用控制器重定向请求。为此使用Controller.RedirectToAction方法。

