1

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.

Medeni Baykal
  • 4,223
  • 1
  • 28
  • 36
Berk
  • 11
  • 1
  • 3
  • is the primary intent here to determine if the user is allowed to access Index, or are you specifically attempting to determine the results of an if/else statement inside of an ActionMethod? – Neurothustra Mar 21 '14 at 21:43
  • 1
    What you have will display either the index or error page when they access the /login page depending on the value of `str`. Was there something else you wanted to do? – Andy T Mar 21 '14 at 22:04
  • i have my own backend library that turns me a response which i can see is it succeed or failed that corresponds to user can login or not.After i check user can login i want to navigate my user to my main page which is in an another view called it index. – Berk Mar 21 '14 at 22:21
  • so what is your problem? what is not working? the code above works – card_master Mar 22 '14 at 07:27

3 Answers3

2

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.

Community
  • 1
  • 1
Medeni Baykal
  • 4,223
  • 1
  • 28
  • 36
0

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();}
Neurothustra
  • 300
  • 1
  • 5
  • 14
0

you can use:

RedirectToAction("actionName", "controllerName");
Linh Tuan
  • 440
  • 3
  • 11