Gonzalo
Gonzalo

Reputation: 2876

Redirect from a [HttpGet] Action To [HttpPost] Action - MVC3

I want to redirect to a [HttpPost] Action from a [HttpGet] Action in the same controller.

Is it possible?

I'm trying to not rewrite the same code for a Login, because it is a complex, and not typical logon function

This is my code:

[HttpGet]
public ActionResult Login(){
    return View();
}

[HttpPost]
public ActionResult Login(LoginModel model)
{
    //search user and create sesion
    //...

    if (registered)
        {
        return this.RedirectToAction("Home","Index");                      
        }else{
        return this.RedirectToAction("Home", "signIn");
    }
}

[HttpGet]
public ActionResult signIn(){
    return View();
}

[HttpGet]
public ActionResult signInUserModel model)
{
    //Register new User
    //...
    if (allOk)
        {
        LoginModel loginModel = new LoginModel();
            loginModel.User = model.User;
            loginModel.password = model.password;

            //next line doesn't work!!!!!
        return this.RedirectToAction("Home","Login", new { model = loginModel); 

        }else{
        //error
        //...

    }

}

Any help would be appreciated.

Thanks

Upvotes: 2

Views: 6522

Answers (3)

ajd
ajd

Reputation: 523

You can return a different View from the method name

public ActionResult signInUserModel model)
{
    ...
    return View("Login", loginModel);
}

Bit late, but I just had the same issue...

Upvotes: 3

Adriano Silva
Adriano Silva

Reputation: 2576

It is possible. All actions must be in the same controller.

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

[HttpPost]
public ActionResult Login(LoginModel model)
{
    //search user and create sesion
    //...

    if (registered)
    {
        return RedirectToAction("Index");
    }

    return View(model);
}

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

[HttpPost]
public ActionResult SignIn(UserModel model)
{
    //Register new User
    //...
    if (allOk)
    {
        return RedirectToAction("Login");
    }

    return View(model);
}

Upvotes: 1

AdaTheDev
AdaTheDev

Reputation: 147324

You could refactor the core login logic out from the Post method and then call that new method from both places.

e.g. Suppose you create a LoginService class to handle logging someone in. It's just a case of using that from both your actions, so no need to redirect from one action to the other

Upvotes: 2

Related Questions