In this blog you will learn how to Redirect from One Controller Action to Another. Step1: Create an ASP.net MVC project. Choose ASP.Net MVC project from template and Press Next, then name the empty project as RoutingExample and click ok. Step 2: Add two controllers.
An ActionResult is a return type of a controller method in MVC. Action methods help us to return models to views, file streams, and also redirect to another controller's Action method.
Use the overloads that take the controller name too...
return RedirectToAction("Index", "MyController");
and
@Html.ActionLink("Link Name","Index", "MyController", null, null)
try:
public ActionResult Index() {
return RedirectToAction("actionName");
// or
return RedirectToAction("actionName", "controllerName");
// or
return RedirectToAction("actionName", "controllerName", new {/* routeValues, for example: */ id = 5 });
}
and in .cshtml
view:
@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 */ })
Notice using null
in final expression is not recommended, and is better to use a blank new {}
instead of null
You can use the following code:
return RedirectToAction("Index", "Home");
See RedirectToAction
You can use the overloads method RedirectToAction(string actionName, string controllerName);
Example:
RedirectToAction(nameof(HomeController.Index), "Home");
You can use local redirect. Following codes are jumping the HomeController's Index page:
public class SharedController : Controller
{
// GET: /<controller>/
public IActionResult _Layout(string btnLogout)
{
if (btnLogout != null)
{
return LocalRedirect("~/Index");
}
return View();
}
}
Most answers here are correct but taken a bit out of context, so I will provide a full-fledged answer which works for Asp.Net Core 3.1. For completeness' sake:
[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"
}
}
If you try to use any of the url-specific strings, e.g. "some_health_url"
, it will not work!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With