ASP.NET MVC > Redirect

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 RedirectToRoute method 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.


 Views: 79650 | Post Order: 57



Write for us






Hosting Recommendations