@using (Ajax.BeginForm("Login", "Account", "",
new AjaxOptions { HttpMethod = "POST" },
new { id = "loginForm", name = "loginForm" }))
{
...
}
This form perform a request and receive a response 200 OK. Debbuging I can see the response html but I don´t get redirected.
If I do it manually without using html helps I get successfully redirected to where I need to.
This is the controller:
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model)
{
MembershipProvider mp = Membership.Provider;
bool isDigital = bool.Parse(Request.Form.GetValues("hasDigital")[0]);
string certDBNumber;
if (isDigital)
{
/*** Retira só o que enteressa do Certificado.Subject (CPF/CNPJ)*/
string code = Request.Form.GetValues("code")[0];
string[] dataArray = code.Split(',');
string data = dataArray.Last();
string[] numberArr = data.Split(':');
string number = numberArr.Last();
/*** Resgata chave do usuário no banco ***/
using (tgpwebgedEntities context = new tgpwebgedEntities())
{
var userObj = from u in context.aspnet_Users
where u.UserName == model.UserName
select u.UserId;
Guid userID = userObj.First();
var obj = from u in context.sistema_UsersCertified
where u.userID == userID select u.keyNumber;
certDBNumber = obj.First();
}
//Verifica se usuário é credenciado
if (number == certDBNumber) {
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home");
}
}//Login sem certificado digital
else
{
if (ModelState.IsValid &&
mp.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home");
}
}
/*** Se chegou até aqui algo deu errado. Mostra denovo o form ***/
ModelState.AddModelError("", "Username ou Password incorreto!.");
return View(model);
}
Why this strange behavior?
As a result of this being an ajax post, you cannot redirect. An option would be to return a value such that the success function realized the redirection needed to take place, and then issued
Alternatively, you could make a redirection view
RedirectionView.cshtml
And then return this view from your ajax post and it would redirect.
Edit
This got more attention than I expected, so I thought I would improve this answer a little bit with two more complete examples.
1: jQuery’s ajax
view:
controller:
2: RedirectionView.cshtml
main view:
RedirectionView.cshtml
Controller