返回消息到用于登录的引导程序模态 [英] Return message to bootstrap modal used for login

查看:98
本文介绍了返回消息到用于登录的引导程序模态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Bootstrap模式建立具有登录名的网站.如果用户输入了错误的用户名或密码,我希望它在模式上显示一条消息.我已经能够通过ajax将消息作为json传递,但IE尝试将json下载为文件,然后Chrome在浏览器窗口中将其打开.我如何才能停止这样做?

I'm building a website with the login in a bootstrap modal. If a user enters a wrong username or password, I want it to display a message on the modal. I've been able to pass the message as json via ajax, but IE tries do download the json as a file, and Chrome opens it in a browser window. How do I get it to stop doing this?

登录表单位于以模式显示的部分视图中:

The login form is in a partial view that renders in the modal:

<!-- LOGIN  MODAL -->
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title">Log In to your Account</h4>
</div>

<div class="modal-body">

    <p id="failedloginmessage" class="alert-danger"></p>

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

        <div class="loginForm">

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class="form-group">
                @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label" })

                @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control", id = "txtUserName" } })
                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label" })

                @Html.PasswordFor(model => model.Password, htmlAttributes: new { @class = "form-control", placeholder = "Password", id = "txtPassword" })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>


            <div class="form-group">
                <button id="btnlogin" type="submit" class="btn btn-primary btn-block">Log In</button>
            </div>
        </div>

        <div class="checkbox">
            <label><input type="checkbox"> Remember me</label>
            <a href="#" class="pull-right link">Forgot Password?</a>
        </div>
    }

</div>

按钮单击触发我的jquery:

My jquery triggered by the button click:

$("#btnlogin").click(function () {

    $.ajax({
        url: "/Login/Login",
        type: "POST",
        datatype: 'application/json',
        contentType: 'text/html',
        data: $("#loginForm").serialize(),
        success: function (result) {
            if (result.success === "false")
                $("#failedloginmessage").html(result.response);
            }
        })       
});

我的登录控制器:

[HttpPost]
public ActionResult Login(CModel model)
{
    try
    {
        Person user = new Person(model.UserName, model.Password);

        if (user.Login())
        {
            Session["user"] = user;

            return RedirectToAction("Index", "User");
        }
        else
        {
            var result = new { success = "false", response = "User name or password is incorrect." };

            return Json(result, JsonRequestBehavior.AllowGet);
        }             
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

推荐答案

正在打开新的浏览器窗口,因为您正在执行常规表单提交!

It is opening a new browser window because you are doing a normal form submit!

为什么要进行普通表单提交? 因为即使您有一些代码来关联提交"按钮上的click事件以进行ajax发布,您也不会停止常规表单的提交行为,因此也会使常规表单提交成为可能.

Why is it doing a normal form submit ? Because even though you have some code to wireup click event on the submit button to do an ajax post, you are not stopping the normal form submit behavior, hence it is making the normal form submit as well.

您可以使用jquery preventDefault()方法来阻止常规表单提交.

You can use the jquery preventDefault() method to prevent the normal form submit.

从ajax调用中调用的action方法返回Redirect响应也没有意义.您应该返回一个JSON响应.

Also there is no point in returning a Redirect response from an action method which is being called from ajax call. You should return a JSON response back.

[System.Web.Mvc.HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult Login(CModel model)
{
    try
    {
        if (yourIfConditionToCheckCredentialsGoesHereNow)
        {
            return Json(new { success = true ,url = Url.Action("Index","User") });
        }
        else
        {
            return Json(new { success = false, response = "Password is incorrect." });
        }
    }
    catch (Exception ex)
    {
        return Json(new { success = false, response = "Error processing!" });
    }
}

然后在$.ajax调用的成功/完成处理程序中,检查响应并根据需要执行下一步(显示消息/将用户重定向到/users/index页面)

And in the success/done handler of $.ajax call, check the response and do the next step as needed (show message/ redirect user to the /users/index page)

$(function () {

    $("#btnlogin").click(function (e) {
        e.preventDefault();

        $.ajax({
            url: $("#loginForm").attr("action"),
            type: "POST",
            data: $("#loginForm").serialize(),
        }).done(function(result) {
            if (!result.success) {
                $("#failedloginmessage").html(result.response);    
            } else {
                alert('successful login');
                window.location.href = result.url;
            }
        }).fail(function(x, a, e) {
            alert(e);
        });
    });

});

您还可以考虑在表单的submit事件上进行布线,而不是在按钮上的click事件上进行布线.当用户在输入输入表单元素值后单击Enter按钮时,它将提交表单.

You might also consider wiring up on the submit event of the form instead of the click event on the button.When user clicks enter button after entering the input form element values, it will submit the form.

$("#loginForm").submit(function (e) {
    e.preventDefault();

    $.ajax({
        url: $(this).attr("action"),
        type: "POST",
        data: $(this).serialize()
    }).done(function(result) {
        //existing code to check result
    }).fail(function(x, a, e) {
        alert(e);
    });
});

这篇关于返回消息到用于登录的引导程序模态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆