In ASP.NET MVC, the RedirectToAction
method is used to redirect the user's browser to another action method within the same or a different controller. Here's an example of how to use RedirectToAction
in a controller action method:
csharppublic ActionResult MyAction()
{
// Do some work
// Redirect the user to the "Index" action method in the "Home" controller
return RedirectToAction("Index", "Home");
}
In this example, the MyAction
method redirects the user to the Index
action method in the Home
controller. The RedirectToAction
method takes two parameters: the name of the action method to redirect to, and the name of the controller that contains the action method. The method returns a RedirectToActionResult
that tells the MVC framework to redirect the user's browser to the specified action method.
You can also pass route values to the action method you're redirecting to. Here's an example:
csharppublic ActionResult MyAction()
{
// Do some work
// Redirect the user to the "Details" action method in the "Products" controller,
// passing the product ID as a route value
return RedirectToAction("Details", "Products", new { id = 123 });
}
In this example, the MyAction
method redirects the user to the Details
action method in the Products
controller, passing the product ID 123
as a route value. The RedirectToAction
method takes a third parameter that is an object containing the route values to pass to the action method being redirected to. These route values will be used to generate the URL that the user's browser will be redirected to.
Comments
Post a Comment