I’m trying to redirect the user if they login successfully but the code I have on my page seems to be preventing the redirection from working. If I remove the jQuery below the redirection works. Can somebody tell me tell me if there’s something I’m doing wrong? Thanks
I have the following Action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(User user)
{
var myErrors = new Dictionary<string, string>();
try
{
if (ModelState.IsValid)
{
if (userRepository.ValidUser(user))
{
return RedirectToAction("Index", "Group", new {page = (int?)null});
}
else
{
return Json("Username or password seems to be incorrect");
}
}
else
{
foreach (KeyValuePair<string, ModelState> keyValuePair in ViewData.ModelState)
{
if (keyValuePair.Value.Errors.Count > 0)
{
List<string> errors = new List<string>();
myErrors.Add(keyValuePair.Key, keyValuePair.Value.Errors[0].ErrorMessage);
}
}
return Json(myErrors);
}
}
catch (Exception)
{
return Json("Invalid");
}
}
and the following code on my page:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#SaveSuccess").hide();
$("#btnLogin").click(function() {
$("form").submit(function(event) {
var formData = $(this).serialize();
$.post($(this).attr("action"), formData, function(res) {
ShowErrors(res);
if (res == true) {
$("#SaveSuccess").text("Saved");
}
else {
$("#divError").html(res);
}
$("#SaveSuccess").fadeIn(100);
}, "json");
return false;
});
});
});
</script>
You should have a look at this question, your issue is that it’s sending a 302 (IIRC, it’s early) in response to the AJAX request, not an overall page request, so you need to look for that header and redirect the entire page if it’s found.
The approach in the top answer there is probably as neat as it gets cross-browser, just return JSON with a redirect url and redirect to that url, like this:
On the C# Side something like this instead of the redirect: