Redirection in ASP.NET MVC:-
Using this we can redirect from one controller to another using the controller method,ASP.NET MVC provides three different types of ActionResult method for Redirection.
1) Redirect() :-
Using this we can redirect from one controller to another using the controller method,ASP.NET MVC provides three different types of ActionResult method for Redirection.
1) Redirect() :-
We can pass the complete URL under redirect(), we will use the web URL of the current application or cross-application using Redirect().
public ActionResult Methodname()
{
return Redirect("url");
}
Example:-
public class URLRedirectionController : Controller
{
//
// GET: /URLRedirection/
public ActionResult Index()
{
// return Redirect("http://shivatutorials.com");
return Redirect("Home/Index");
}
}
2) RedirectToAction():- We can pass Action name and Controller name under RedirectToAction(). It will work using Single Parameters and Multiple Parameters.
public ActionResult Methodname()
{
// return RedirectToAction("Methodname"); //same controller
return RedirectToAction("Methodname","Controllername"); // cross controller
}
Example of RedirectToAction:-
public ActionResult Methodname()
{
// return RedirectToAction("Methodname"); //same controller
return RedirectToAction("Methodname","Controllername"); // cross controller
}
Example of RedirectToAction:-
public class URLRedirectionController : Controller
{
//
// GET: /URLRedirection/
public ActionResult Index()
{
// return RedirectToAction("Index", "Home");
return RedirectToAction("About");
}
public ActionResult About()
{
return View();
}
}
3) RedirectToRoute() :-
We can pass Actionname and Controllername using Routename by routeconfig.cs under RedirectToRoute().
It will work using route name ;
public ActionResult Methodname()
{
return RedirectToRoute("Routername");
}
First Create Custom Route under routeconfig.cs file and custom route should be defined before of default routing path.
public ActionResult Methodname()
{
return RedirectToRoute("Routername");
}
First Create Custom Route under routeconfig.cs file and custom route should be defined before of default routing path.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "CustomRoute",
url: "{controller}/{action}/{id}",
defaults: new { controller = "URLRedirection", action = "About", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "URLRedirection", action = "Index", id = UrlParameter.Optional }
);
}
}
Create Controller and Write Following Code:-
public class URLRedirectionController : Controller
{
//
// GET: /URLRedirection/
public ActionResult Index()
{
return RedirectToRoute("CustomRoute");
}
public ActionResult About()
{
return View();
}
}
POST Answer of Questions and ASK to Doubt