I have created a sample ASP.NET MVC website in VS 2015 and in a view i am using the extension Ajax.BeginForm to post login credentials to controller, and on OnSuccess callback i want to check for server errors and if any show the error to user else - redirect to home page, here is the code (It returns always error intentionally to test the callback):
Model
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
View
<script>
function onLogInSuccess(result) {
/*
Instead of getting here after returning the result from
Controller all the view(in the browser) is replaced with:
{"status":"ERROR","message":"Invalid Email or Password.","returnUrl":"/"}
*/
if (result.status === "OK") {
window.location.href = result.returnUrl;
} else {
alert(result.message);
}
}
$("#buttonLogIn").on('click', function (e) {
$("#formLogIn").submit();
});
</script>
<section id="loginForm">
@using (Ajax.BeginForm("LogIn", "Custom", null, new AjaxOptions { HttpMethod = "POST", OnSuccess = "onLogInSuccess" }, new { @class = "form-horizontal", role = "form", id = "formLogIn" }))
{
@Html.AntiForgeryToken()
<h4>Login:</h4>
<hr />
<div class="form-group">
<label id="loginValidation" class="col-md-12 validation-label"></label>
</div>
<div class="form-group">
<label class="col-md-12 control-label" for="LogInUsername">Username</label>
<div class="col-md-12">
<input class="form-control" id="LogInUsername" name="Username" type="text" value="" />
</div>
</div>
<div class="form-group">
<label class="col-md-12 control-label" for="LogInPassword">Password</label>
<div class="col-md-12">
<input class="form-control" id="LogInUsername" name="Password" type="password" value="" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-12">
<input type="button" id="buttonLogIn" value="Log in" class="btn btn-default" />
</div>
</div>
}
</section>
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult LogIn(LoginModel Credentials)
{
string returnUrl = "/";
string status = AsyncRequestStatus.ResultError; //"ERROR"
string message = "Invalid Email or Password.";
return Json(new { status = status, message = message, returnUrl = returnUrl });
}