首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >禁用Ajax post MVC 5后重定向到控制器

禁用Ajax post MVC 5后重定向到控制器
EN

Stack Overflow用户
提问于 2019-04-10 03:51:52
回答 1查看 396关注 0票数 0

我在_Layout上有一个锚点,用来调用一个modal,并用一个操作来获得一个显示modal的局部视图

<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>

此操作将转到此控制器

public class AccountController : Controller
{
    public ActionResult LoginModal()
    {
        return PartialView("_PartialLogin");
    }

  ...

这是带有模式的局部视图

    @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>

在我使用ajax在模式中提交表单之前,一切都很正常。

这是我在提交后转到的控制器

  // 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" });
    }

这是问题所在。提交表单后,我被重定向到localhost:port/Account/Login,如果出现错误,它会显示json的内容。我只想在ajax成功时检索错误,并在模型上打印错误...为什么我会被重定向到带有json内容的控制器?

在我在stackoverflow中看到的另一篇文章中,我在ajax配置中添加了一些选项,但显然没有改变我的情况。

我只想保持我的模式,并收到成功或出错的状态消息。如果出现错误,我只需刷新ajax成功页面以显示已登录的html

EN

回答 1

Stack Overflow用户

发布于 2019-04-10 04:00:35

$("form").submit((e) => {
	e.preventDefault();
  
  alert("No redirect");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  First name:<br>
  <input type="text" name="firstname"><br>
  Last name:<br>
  <input type="text" name="lastname">
  <button type="submit"> Submit </button>
</form>

您需要禁用窗体的默认行为

event.preventDefault();

$("#formModal").submit(function () {

event.preventDefault();

// rest of your code here


// ajax request 
// or use form.submit()

// form.reset() to reset the form state.
}

因为您是通过Ajax发送表单请求的,所以我不认为您需要使用form.submit(),但是您可能会发现form.reset()很有用。

你可以阅读更多关于HTMLFormElement是如何工作的here

干杯

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55600340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档