【问题标题】:Need to redirect to another page in asp.net MVC3需要重定向到asp.net MVC3中的另一个页面
【发布时间】:2012-09-12 11:59:40
【问题描述】:

我正在使用 ASP.net 和 MVC3 。当会话过期时,我需要显示一个弹出窗口或转到登录页面。谁能告诉我如何重定向到操作名称为“index”且控制器名称为“Home”的登录页面。

我的代码是:

此方法在我的模型中。在此模型中,我必须重定向到登录页面。

protected Product GetCurrentCorp(HttpContextBase context)
    {

        if (context.Session != null)
        {
            var selectedProduct = context.Session["SelectedProduct"];
            if (selectedProduct != null)
            {
                var product= selectedProduct as Product;
                return product;                   
            }
        }
        // Here I need to redirect to index page(login page)
        throw new ArgumentException("Product is not set, Cannot Continue.");
    } 

【问题讨论】:

  • 为什么要访问模型内​​部的HttpContext和Session?
  • 你不需要从你的模型中重定向,你需要在控制器的 action 方法中这样做。
  • @nan:仅在此模型中,我正在检查用户凭据的授权。所以我只需要在这里重定向。

标签: c# asp.net-mvc asp.net-mvc-3


【解决方案1】:

如果 LoggedOn 是您的 Action 而 Account 是您的 Controller,那么您可以将代码编写为:

return RedirectToAction("LoggedOn", "Account");

希望对你有帮助。!!!

【讨论】:

  • RedirectToAction 只能在控制器中访问。我无法访问我的模型类文件。我们是否需要添加任何命名空间来访问此 RedirectToAction 方法?
  • 模型类中无法访问 RedirecToAction 方法。
  • 你能告诉我如何从模型重定向到登录页面吗?
  • 您对 MVC 的概念不清楚。请看这里asp.net/mvc/overview/what-is-mvc
【解决方案2】:

【讨论】:

  • 基本上你的控制器负责重定向。模型不应该这样做。
  • 那么我们如何在模型中访问它呢?你能给我一些建议吗?
  • 简单地从控制器调用模型并检查控制器中返回的产品。如果从模型返回的产品在控制器中为空,则使用 RedirectToAction
【解决方案3】:

这是向您展示重定向到不同操作或 URL 的示例的自包含操作。

public ActionResult MyAction()
{
  // Use this for action, can also be used to redirect 
  // to action on different controller by adding parameter
  return RedirectToAction("MyActionName");

  // Use this for URL
  return Redirect("http://example.com/foo/bar");
}

希望对你有所帮助。

【讨论】:

    【解决方案4】:

    您可以使用RedirectToAction()

    return RedirectToAction("ActionName", "ControllerName");
    

    【讨论】:

    • 在模型中我们不能访问 RedirectToAction()。有没有其他办法?
    猜你喜欢
    • 1970-01-01
    • 2012-06-11
    • 2014-07-21
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多