Redirect user to another route url in ASP.NET MVC

How to redirect the user to another route url?

To redirect user to another route url from action method of the controller, we can use RedirectToRoutemethod by passing route name defined in the App_Start/RouteConfig.cs file.
ROUTECONFIG.CS
routes.MapRoute(
    name: "MyCustomRoute",
    url: "MyEmployees/{action}/{id}",
          defaults: new { controller = "PersonalDetail", action =
      "Create", id = UrlParameter.Optional }
);
Here, our Route name is “MyCustomRoute” and if any user comes with the url starting with “MyEmployees”, this route serves the request.
CONTROLLER CODE
public ActionResult OutputToAction()
        {
             return RedirectToRoute("MyCustomRoute", new { Id = 5 });
        }
When above action method executes, it gives the url formed by MyCustomRoute defined in the RouteConfig.cs based in object parameter (2nd parameter) passed.
POINT OF INTEREST
There are few overloads of RedirectToRoute method that help us to redirect to another routes, try different overload methods by passing respective parameters.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...