2011-10-25 31 views
89

我一直在寻找通过努力找到一些方式来重定向到来自另一个控制器的Index视图。如何重定向到另一个控制器的索引?

public ActionResult Index() 
{     
    ApplicationController viewModel = new ApplicationController(); 
    return RedirectToAction("Index", viewModel); 
} 

这就是我现在试过的。现在我得到的代码有一个ActionLink,链接到我需要的页面Redirect

@Html.ActionLink("Bally Applications","../Application") 

回答

209

请使用带控制器的名字太重载...

return RedirectToAction("Index", "MyController"); 

@Html.ActionLink("Link Name","Index", "MyController", null, null) 
+3

好这个工作。我之前尝试过这样做的时候肯定是一个错字。 – cjohnson2136

+2

这样做会更快的,但有一个计时器停止我 – cjohnson2136

+0

啊,对于我们新手MVC,这是非常有用的。只是简单地重定向到另一个不同控制器所代表的不同文件夹中的另一个视图,直到我阅读完为止。 – atconway

12

您可以使用下面的代码:

return RedirectToAction("Index", "Home"); 

RedirectToAction

+0

我试过了,它不起作用。它给了我页找不到错误 – cjohnson2136

+0

应符合“控制器”: '返回RedirectToAction(“指数”,“家”);' – Hiraeth

+0

我需要使用“/索引”,否则没有发现 – code4j

22

尝试:

public ActionResult Index() { 
    return RedirectToAction("actionName"); 
    // or 
    return RedirectToAction("actionName", "controllerName"); 
    // or 
    return RedirectToAction("actionName", "controllerName", new {/* routeValues, for example: */ id = 5 }); 
} 

.cshtml观点:

@Html.ActionLink("linkText","actionName") 

OR:

@Html.ActionLink("linkText","actionName","controllerName") 

OR:

@Html.ActionLink("linkText", "actionName", "controllerName", 
    new { /* routeValues forexample: id = 6 or leave blank or use null */ }, 
    new { /* htmlAttributes forexample: @class = "my-class" or leave blank or use null */ }) 

注意在最后的表达式中使用null不推荐,而最好使用空白new {}代替null

+3

关于您的通知,出于什么原因使用'new {}'而不是'null'更好? – musefan

1

您可以使用本地重定向。 下列代码跳的HomeController的索引页:

public class SharedController : Controller 
    { 
     // GET: /<controller>/ 
     public IActionResult _Layout(string btnLogout) 
     { 
      if (btnLogout != null) 
      { 
       return LocalRedirect("~/Index"); 
      } 

      return View(); 
     } 
} 
1

可以使用重载方法RedirectToAction(string actionName, string controllerName);

例子:

RedirectToAction(nameof(HomeController.Index), "Home"); 
相关问题