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.
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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With