C# 在Ajax post MVC 5之后禁用重定向到控制器
我在_布局上有一个锚,用来调用一个模态,并通过一个动作获得一个局部视图来显示模态C# 在Ajax post MVC 5之后禁用重定向到控制器,c#,ajax,asp.net-mvc-5,modal-dialog,C#,Ajax,Asp.net Mvc 5,Modal Dialog,我在_布局上有一个锚,用来调用一个模态,并通过一个动作获得一个局部视图来显示模态 <ul class="navbar-nav mr-auto"> <li class="nav-item"> @Html.Action("LogoutModal", "Account") <a class="nav-link" href="#" data-toggle="modal" data-target="#modalLogout">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
@Html.Action("LogoutModal", "Account")
<a class="nav-link" href="#" data-toggle="modal" data-target="#modalLogout">
Log Out
</a>
</li>
</ul>
这是模态的局部视图
@model HutLogistica.ViewModels.LoginViewModel
@{
Layout = null;
}
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/login.css" rel="stylesheet" />
<link href="~/Content/fontawesome-all.css" />
<script src="~/scripts/jquery-3.3.1.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/fontawesome/all.js"></script>
<!-- Modal -->
<div class="modal fade" id="modalLogin" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "formModal" }))
{
@Html.AntiForgeryToken();
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control form-control-lg", placeholder = "Username", autofocus = true } })
@Html.ValidationMessageFor(model => model.Username, "")
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control form-control-lg", placeholder = "Password" } })
@Html.ValidationMessageFor(model => model.Password, "")
@Html.EditorFor(model => model.RememberMe, new { htmlAttributes = new { @class = "custom-control-input", id = "customCheck" } })
<button type="submit" class="btn btn-info">
Entrar
</button>
}
<div id="loader" class="text-center p-3 d-none">
<div class="lds-circle"><div></div></div>
<p><span class="text-muted">Aguarde...</span></p>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ajaxStart(function () {
$("#loader").removeClass('d-none');
});
$(document).ajaxStop(function () {
$("#loader").addClass('d-none');
});
$(function () {
$("#formModal").submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
cache: false,
processData: false,
contentType: false,
data: $(this).serialize(),
success: function (status, response) {
if (response.success) {
alert('Autenticado com sucesso');
$('#loginModal').modal('hide');
//Refresh
location.reload();
} else {
alert(response.responseText);
}
},
error: function (response) {
alert(response.data.responseText)
}
});
}
return false;
});
</script>
问题就在这里。提交表单后,我会被重定向到localhost:port/Account/Login,如果有错误,会显示json的内容。我只想在ajax success上检索错误并在modal上打印错误。。。为什么我被重定向到带有json内容的控制器
我在stackoverflow中看到的另一篇文章中为ajax配置添加了一些选项,但显然没有改变我的情况
我只想停留在我的模态上,接收状态消息成功或出现错误。若有错误,我只需刷新ajax成功页面,以显示登录的html更改
@使用(Html.BeginForm(“Login”,“Account”,FormMethod.Post,new{id=“formModal”}))
到
@使用(Html.BeginForm(“LoginModal”,“Account”,FormMethod.Post,new{id=“formModal”}))
$(“表格”)。提交((e)=>{
e、 预防默认值();
警报(“无重定向”);
});代码>
名字:
姓氏:
提交
它将我重定向到../Account/LoginModal,但这不起作用,我必须将模型发送到登录名,而LoginModali之前已经这样做了,有人说底部返回false就足够了。然而,它仍然用每一种方法重定向我。我假设是什么原因导致页面刷新,但我无法用JSFIDLE链接找出答案的日期。试试看。注释掉e.preventDefault()
查看之前和之后。ok我似乎设法找到了导致页面刷新的原因,如果($(this).valid()),则jquery验证是非结构化的,但是如果我删除此项,则我的客户端验证将被忽略
@model HutLogistica.ViewModels.LoginViewModel
@{
Layout = null;
}
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/login.css" rel="stylesheet" />
<link href="~/Content/fontawesome-all.css" />
<script src="~/scripts/jquery-3.3.1.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/fontawesome/all.js"></script>
<!-- Modal -->
<div class="modal fade" id="modalLogin" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "formModal" }))
{
@Html.AntiForgeryToken();
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control form-control-lg", placeholder = "Username", autofocus = true } })
@Html.ValidationMessageFor(model => model.Username, "")
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control form-control-lg", placeholder = "Password" } })
@Html.ValidationMessageFor(model => model.Password, "")
@Html.EditorFor(model => model.RememberMe, new { htmlAttributes = new { @class = "custom-control-input", id = "customCheck" } })
<button type="submit" class="btn btn-info">
Entrar
</button>
}
<div id="loader" class="text-center p-3 d-none">
<div class="lds-circle"><div></div></div>
<p><span class="text-muted">Aguarde...</span></p>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ajaxStart(function () {
$("#loader").removeClass('d-none');
});
$(document).ajaxStop(function () {
$("#loader").addClass('d-none');
});
$(function () {
$("#formModal").submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
cache: false,
processData: false,
contentType: false,
data: $(this).serialize(),
success: function (status, response) {
if (response.success) {
alert('Autenticado com sucesso');
$('#loginModal').modal('hide');
//Refresh
location.reload();
} else {
alert(response.responseText);
}
},
error: function (response) {
alert(response.data.responseText)
}
});
}
return false;
});
</script>
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var user = Authenticate(model);
if (user != null)
{
var ticket = new FormsAuthenticationTicket(
1,
user.Id.ToString(),
DateTime.Now,
DateTime.Now.AddHours(5),
model.RememberMe,
user.Roles.Select(c => c.Nome).FirstOrDefault(),
FormsAuthentication.FormsCookiePath
);
Response.Cookies.Add
(
new HttpCookie
(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket)
)
);
return Json(new { success = true });
}
else
{
ModelState.AddModelError("", "Username / Password incorrectos");
return Json(new { success = false, responseText = "Username / Password incorrectos" });
}
}
else
return Json(new { success = false, responseText = "Dados inválidos" });
}