Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect within a ViewResult or ActionResult function?

Tags:

asp.net-mvc

Say I have:

public ViewResult List() 
{
    IEnumerable<IModel> myList = repository.GetMyList();
    if(1 == myList.Count())
    {
        RedirectToAction("Edit", new { id = myList.Single().id });
    }

    return View(myList);
}

Inside this function, I check if there is only one item in the list, if there is I'd like to redirect straight to the controller that handles the list item, otherwise I want to display the List View.

How do I do this? Simply adding a RedirectToAction doesn't work - the call is hit but VS just steps over it and tries to return the View at the bottom.

like image 992
Pete Avatar asked Mar 29 '10 14:03

Pete


People also ask

How we can redirect to another page or controller?

Redirect() method The first method od redirecting from one URL to another is Redirect(). The Rediect() method is available to your controller from the ControllerBase class. It accepts a target URL where you would like to go.

What is the difference between ActionResult and ViewResult?

ActionResult is an abstract class, and it's base class for ViewResult class. In MVC framework, it uses ActionResult class to reference the object your action method returns. And invokes ExecuteResult method on it. And ViewResult is an implementation for this abstract class.

Can I return ActionResult instead of ViewResult?

First to Understand---ActionResult and ViewResult are basically a return type for an method(i.e Action in MVC). Second The Difference is --- ActionResult can return any type of Result Whereas ViewResult can return result type of View Only.

Which ActionResult redirect to another action method by using its URL?

RedirectResult is an ActionResult that returns a Found (302), Moved Permanently (301), Temporary Redirect (307), or Permanent Redirect (308) response with a Location header to the supplied URL. It will redirect us to the provided URL, it doesn't matter if the URL is relative or absolute.


1 Answers

You need to return RedirectToAction instead of just calling the RedirectToAction method. Also, your method will need to return an ActionResult is a return type compatible with both ViewResult and RedirectToRouteResult.

public ActionResult List() 
{
    IEnumerable<IModel> myList = repository.GetMyList();
    if(1 == myList.Count())
    {
        return RedirectToAction("Edit", new { id = myList.Single().id });
    }

    return View(myList);
}
like image 66
Jim Counts Avatar answered Oct 21 '22 07:10

Jim Counts