Berk
Berk

Reputation: 11

How to Redirect to Another Action in an Action.

I'm trying to change the current view via controller.

public ActionResult login(string str)
{
  if(str=="true")
  {
    return View("index");
  }
  else
  {
    return View("error");
  }
}

public ActionResult index()
{
  return View();
}

public ActionResult error()
{
  return View();
}

I have all this actions in the same controller and the view files in the same directory.

Upvotes: 1

Views: 4155

Answers (3)

Linh Tuan
Linh Tuan

Reputation: 448

you can use:

RedirectToAction("actionName", "controllerName");

Upvotes: 0

Medeni Baykal
Medeni Baykal

Reputation: 4333

I think you're trying redirect to another action from one. You can use RedirectToAction(..) function the achive this.

For example, if your action defined like this:

public ActionResult Action1()
{
   /* code omitted */
}

You can redirect to it like this any where in an action:

return RedirectToAction("Action1");

If you want to redirect to an action which is in another controller, you can use

return RedirectToAction("Action1", "ControllerName");

If the action takes parameters, or route parameters you can use

return RedirectToAction("Action1", "ControllerName", new { param1 = value1, param2 = value2 });

BTW, If you're trying to implement an authentication mechanism, this is the wrong approach. You should use [Authorize] attribute or develop custom authentication. You can read this.

Upvotes: 2

Neurothustra
Neurothustra

Reputation: 297

Since it appears that you are looking to validate a user before allowing them access to Index, MVC has a built-in class attribute that you can use which will reroute the user to a login form for you.

[Authorize]
public ActionResult Index()
{return View();}

Upvotes: 0

Related Questions