Skip to main content

RedirectToRouteResult in MVC

In this article we will learn about RedirectToRouteResult class.Object of this class represents redirection from one action method to another method within a web application. It sends HTTP 302 response to browser so browser sends another request to new action method.

For example, if login is successful then user will be redirected to dashboard else user will see Invalid Login message.In this case we will use RedirectToRouteResult class.
Below is the syntax for returning object of RedirectToRouteResult class from action method:

return RedirectToAction(“Action Name”,”Controller Name”);

We have to provide target action method where we want to redirect and controller name which contains action method.

Please see below screenshot:

Browser is making request for first action method to server , server is providing 302 (Redirect HTTP status code) as a response to browser, then immediately browser is making another request for second action method to server and after executing second action method, server is providing 200 (OK HTTP status code) as a response to browser.
In this way, we can redirect from one action method to another action method within a web application.

We have added 2 action methods in Home Controller. Below is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult About()
        {
            return View();
        }
        public ActionResult Contact()
        {
            return View();
        }
       
        public ActionResult FirstActionMethod(string username)
        {
            return RedirectToAction("SecondActionMethod","Home");
        }

        public ActionResult SecondActionMethod(string username)
        {
            string message = "Second action method is called";
            return Content(message, "text/plain");
        }
    }
}

We will send request for FirstActionMethod() but it will redirect to SecondActionMethod().

Write below URL in browser address bar and press enter key:
http://localhost:53204/Home/FirstActionMethod

Below is the output: