I have a simple login form on my MVC app (note I'm not using the inbuilt one) which looks something like this:
@using (Html.BeginForm())
{
<label for="UserName" class="placeholder">Email address or username</label>
@Html.TextBoxFor(m => m.UserName)
<label for="Password" class="placeholder">Password</label>
@Html.PasswordFor(m => m.Password)
<button type="submit" title="Log in">Log in ►</button>
}
I have some jquery which should post the data using ajax. If the user is correct then send them off to the correct page otherwise show an error. However I'm struggling. Can anyone point me in the right direction as currently I also get the success even if the account details are incorrect and I've lost the redirect functionality on successful login due to the preventdefault.
$('form').live('submit', function (event) {
// Stop the form from doing a native postback
event.preventDefault();
$.ajax({
type: 'POST',
timeout: 5000,
url: $(this).attr('action'),
data: $('form').serialize(),
success: function (responseHtml) {
// what goes here... as the form is always successful even if the account details are incorrect
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
});
C#
[HttpGet]
public ActionResult Login()
{
if (Session["UserID"] != null)
{
return RedirectToAction("Index", "Home", new { area = "Dashboard" });
}
return View();
}
[HttpPost]
public ActionResult Login(User user, string returnUrl)
{
// Validate the email and password
if (users.Login(user.UserName, user.Password, Request.UserHostAddress))
{
FormsAuthentication.SetAuthCookie(user.UserName, true);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home", new { area = "Dashboard" });
}
}
else
{
return View();
}
}