我在VS 2015中创建了一个示例ASP.NET MVC网站,在视图中我使用扩展Ajax.BeginForm将登录凭据发布到控制器,并且在OnSuccess回调中我想检查服务器错误以及是否有任何显示用户错误 - 重定向到主页,这里是代码(它总是故意返回错误来测试回调):
模型
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
查看
<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>
控制器
[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 });
}
答案 0 :(得分:1)
如果您只显示LogIn()
方法返回的json,那么因为您的视图中未包含jquery.unobtrusive-ajax.js
文件。因此,Ajax.BeginForm()
会回归正常提交
答案 1 :(得分:0)
如果您从服务器端发送一些不同于200的状态代码,则会执行错误回调:
$.ajax({
url: '/foo',
success: function(result) {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('you will see this');
}
});