Asp.Net Mvc Redirect To Action In Another Controller

ASP.NET MVC: Redirect to Action in Another Controller

When working with ASP.NET MVC, you may come across situations where you need to redirect the user to an action method in a different controller.

To achieve this, you can use the RedirectToAction method provided by the ASP.NET MVC framework. This method takes the action name and controller name as parameters and redirects the user to the specified action method in the specified controller.

Example:

Let’s say we have two controllers, HomeController and AdminController, and we want to redirect the user from the Index action in the HomeController to the Index action in the AdminController.

In HomeController:

    
      public class HomeController : Controller
      {
          public IActionResult Index()
          {
              // Redirect to AdminController's Index action
              return RedirectToAction("Index", "Admin");
          }
      }
    
  

In AdminController:

    
      public class AdminController : Controller
      {
          public IActionResult Index()
          {
              return View();
          }
      }
    
  

In the above example, when the user accesses the Index action in the HomeController, they will be redirected to the Index action in the AdminController.

Note that the RedirectToAction method also provides overload versions that allow passing route values as additional parameters. These route values can be used to pass data between the actions.

For example:

    
      return RedirectToAction("Details", "Product", new { id = 123 });
    
  

In this case, the user will be redirected to the Details action in the ProductController, passing the value 123 for the “id” parameter.

It’s important to mention that the RedirectToAction method performs an HTTP 302 (Found) redirect by default. If you need to perform a different type of redirect (e.g., permanent redirect), you can use other methods like RedirectToRoute or RedirectPermanent provided by the ASP.NET MVC framework.

Read more interesting post

Leave a comment