Redirect to Action according to if

Asked

Viewed 50 times

1

I have a Controller:

[HttpPost]
public ActionResult Login(string pUsuario, string pSenha)
{
     usuario oUsuario = modelOff.usuarios.Where(p => p.usuario1 == pUsuario && p.senha == pSenha).SingleOrDefault();
     if (oUsuario == null)
         return IR_PARA_ACTION_1;
     else
         return IR_PARA_ACTION_2;
}

How to select a Action according to the outcome of my if?

1 answer

3


Using RedirectToAction, passing the action name as parameter.

Tip: the extension method SingleOrDefault receives a predicate, you do not need to apply a Where and then SingleOrDefault. In addition, the else is unnecessary.

[HttpPost]
public ActionResult Login(string pUsuario, string pSenha)
{
     usuario oUsuario = modelOff.usuarios.SingleOrDefault(p => 
                                           p.usuario1 == pUsuario && p.senha == pSenha);
     // ^^ Dica 1: Usar apenas SingleOrDefault()

     if (oUsuario == null)
         return RedirectToAction("Action1");

     return RedirectToAction("Action2"); // <- Dica 2: Não precisa do else
}
  • I get an error that not all paths return a value

  • 2

    @Italorodrigo so you didn’t use the code exactly as LINQ posted. His code always returns something.

  • The error is on the line public ActionResult Login(string pUsuario, string pSenha) in the word Login

  • 1

    The semicolon was missing, @Italorodrigo

  • The code ran, but I’m getting a 404 error when sending the form. I’m using the code like this: if (oUsuario == null) { return RedirectToAction("Index"); } else { return RedirectToAction("Login"); }

  • 1

    So it’s because the action doesn’t exist. "index" is in the same controller?

  • To Index is what I start with. It makes the mistake when I go to Login. Just one question: Action is the same as View?

  • 1

    No. Action is the method, view is the cshtml file. It would be good to read this: What are the actions of a controller?

  • So I’m doing it wrong. My idea is to return a View. I’ll see if I can adapt the code here. Thank you.

  • 1

    @Italorodrigo Just create an action for this view.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.