Redirect, RedirectToRoute and RedirectToAction in MVC

Redirect, RedirectToRoute and RedirectToAction in MVC

In this article, I am going to discuss Redirect, RedirectToRoute, and RedirectToAction in MVC application. The ASP.NET MVC has different types of Action Results. Each action result returns a different format of the output. As a programmer, we need to use different action results to get the expected output. Action Results return the result to view the page for the given request. 

We are going to work with the same example that we started in View Result and Partial View Result in ASP.NET MVC article and continue in File Result, Content Result, Empty Result, JavaScript Result and JSON Result in MVC article of this MVC article series.

Redirect Result in MVC

If you wanted to redirect to a URL, then you can use RedirectResult, like this:

public class HomeController : Controller
{
    public RedirectResult Index()
    {
        return Redirect("https://dotnettutorials.net");
    }
}

That works great for redirecting to outside sites from the current application, but not so much for redirecting to other pages within the same application. For that, we can use RedirectToRouteResult.

Redirect result is returning the result to a specific URL. It is rendered to the page by URL. If we give the wrong URL, it will show 404-page errors.

RedirectToRoute Result in MVC

RedirectToRouteResult is used whenever we need to go from one action to another.

public class HomeController : Controller
{
    public RedirectToRouteResult Index()
    {
        return RedirectToRoute(new { controller = "Home", action = "About" });
    }
}

That’s not very friendly though. There’s a better way, an overload of this helper called RedirectToAction:

RedirectToAction Result in MVC

The RedirectToAction Result is returning the result to a specified controller and action method. Controller name is optional in RedirectToAction method. If not mentioned, Controller name redirects to a mentioned action method in the current Controller. Suppose action name is not available but mentioned in the current controller, then it will show a 404 error page.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return RedirectToAction("Login", "Account");
    }
}

In the next article, I am going to discuss HttpStatusCodeResult, HttpUnauthorizedResult, and HttpNotFoundResult in ASP.NET MVC application, Here, in this article, I try to explain Redirect Result, RedirectToRoute Result and RedirectToAction Result in ASP.NET MVC application step by step with a simple example. I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *