【问题标题】:Disable redirect to controller after Ajax post MVC 5在 Ajax 发布 MVC 5 后禁用重定向到控制器
【发布时间】:2019-08-31 04:35:42
【问题描述】:

我在 _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

【问题讨论】:

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


    【解决方案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() 很有用。

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

    干杯

    【讨论】:

    • 我之前已经这样做了,有人说底部的 return false 就足够了。但是,它仍然会用任何一个重定向我。我认为某些原因导致页面刷新,但我不知道是什么
    • 使用 JSFiddle 链接更新了答案。试试看。注释掉e.preventDefault(); 以查看前后对比。
    • 好的,我似乎设法找出导致页面刷新的原因,如果 ($(this).valid()) 是 jquery 验证不显眼,但是如果我删除它,我的客户端验证将被忽略跨度>
    【解决方案2】:

    改变

    @using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "formModal" }))

    @using (Html.BeginForm("LoginModal", "Account", FormMethod.Post, new { id = "formModal" }))

    【讨论】:

    • 它将我重定向到 ../Account/LoginModal,这不起作用,我必须将模型发送到 Login 而不是 LoginModal
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 2016-06-12
    • 1970-01-01
    • 2023-03-13
    • 2012-12-30
    • 2016-08-22
    • 1970-01-01
    相关资源
    最近更新 更多