如何从另一个控制器重定向到 Index?

我一直在寻找从另一个控制器重定向到 Index视图的方法。

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

我现在就是这么做的。现在我给的代码有一个 ActionLink,链接到我需要的网页 Redirect了。

@Html.ActionLink("Bally Applications","../Application")
342710 次浏览

也可以使用带有控制器名称的重载..。

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

还有

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

您可以使用以下代码:

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

参见 RedirectToAction

尝试:

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")

或者:

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

或者:

@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

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

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


return View();
}
}

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

例如:

RedirectToAction(nameof(HomeController.Index), "Home");

完整答案(. Net Core 3.1)

这里的大多数答案都是正确的,但是有点脱离上下文,所以我将提供一个完整的答案,它适用于 Asp。Net Core 3.1.为了完整起见:

[Route("health")]
[ApiController]
public class HealthController : Controller
{
[HttpGet("some_health_url")]
public ActionResult SomeHealthMethod() {}
}


[Route("v2")]
[ApiController]
public class V2Controller : Controller
{
[HttpGet("some_url")]
public ActionResult SomeV2Method()
{
return RedirectToAction("SomeHealthMethod", "Health"); // omit "Controller"
}
}

如果您尝试使用任何特定于 url 的字符串,例如 "some_health_url",它将无法工作!

贴标签助手:

<a asp-controller="OtherController" asp-action="Index" class="btn btn-primary"> Back to Other Controller View </a>

Cs 中有一个方法:

public async Task<IActionResult> Index()
{
ViewBag.Title = "Titles";
return View(await Your_Model or Service method);
}

RedirectToRoute () 是另一个选项。把路线当做论点。另外,使用 nameof ()可能是一个更好的约定,因为您不需要将控制器名称硬编码为字符串。

 return RedirectToRoute(nameof(HomeController) + nameof(HomeController.Index));