简体   繁体   English

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

[英]Disable redirect to controller after Ajax post MVC 5

I have an anchor on the _Layout to call a modal with an action to get a partial view to show modal 我在_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>

this action goes to this controller 这个动作交给这个控制器

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

  ...

and this is the partial view with the modal 这是模态的局部视图

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

everythin works fine until i submit the form in the modal using ajax. 一切都很正常,直到我使用Ajax在模态中提交表单为止。

here is the controller where i go after submit 这是我提交后去的控制器

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

Here is the problem. 这是问题所在。 After i submit the form, i am redirected to localhost:port/Account/Login and shows me the contents of the json if there is an error. 提交表单后,如果存在错误,我将重定向到localhost:port / Account / Login并向我显示json的内容。 I just want to retrieve the error on the ajax success and print on the modal the error... Why am i being redirected to the controller with the json content? 我只想获取有关Ajax成功的错误并在模态上打印错误...为什么我将使用json内容重定向到控制器?

I added a few options to the ajax configuration on another post i saw in stackoverflow but apparently did not change anything in my situation. 我在我在stackoverflow中看到的另一篇文章中的ajax配置中添加了一些选项,但是显然在我的情况下没有任何改变。

I just want to stay on my modal and recieve the status message that was success or there was an error. 我只想继续使用我的模式,并接收成功或出现错误的状态消息。 If there was an error i just refresh page on ajax success to show logged in html 如果有错误,我只是刷新有关ajax成功的页面以显示已登录的html

 $("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> 

You need to disable the forms default behavior 您需要禁用表单的默认行为

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

Since you're sending the form request via Ajax, I do not think you will need to use form.submit() , however you may find form.reset() useful. 由于您是通过Ajax发送表单请求的,所以我认为您不需要使用form.submit() ,但是您可能会发现form.reset()很有用。

You can read more about how HTMLFormElement works here . 您可以在此处阅读有关HTMLFormElement如何工作的更多信息。

Cheers 干杯

Change 更改

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM