在Ajax发布MVC 5后禁用重定向到控制器

时间:2019-04-09 19:51:52

标签: c# ajax asp.net-mvc-5 modal-dialog

我在_Layout上有一个锚点,用于调用带有操作的模态以获取显示模态的局部视图

<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

2 个答案:

答案 0 :(得分:1)

$("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()很有用。

您可以阅读有关here HTMLFormElement的工作原理的更多信息。

欢呼

答案 1 :(得分:0)

更改

@使用(Html.BeginForm(“登录”,“帐户”,FormMethod.Post,新的{id =“ formModal”}))

@using(Html.BeginForm(“ LoginModal”,“ Account”,FormMethod.Post,新{id =“ formModal”}))