如何通过 Ajax 返回无效密码错误消息 - MVC

我有登录页面,用户输入他们的电子邮件和密码,但是当他们输入错误的密码时,我想显示警报或文本,例如(您输入的密码无效)。我已经检查Checkpass不为空做一些事情,否则我不知道我应该做什么老实说。任何人都可以帮助我或指出我正确的方向!


提前致谢:)


控制器:


    [HttpPost]

    public JsonResult Login(string Mail, string pass)

    {


        var hashedPass = PasswordSecurity.PasswordStorage.CreateHash(pass);

        using (DbNameSpace db = new DbNameSpace())

        {

            var query = from cbr in db.Contact_Business_Relation

                        join c in db.Contact on cbr.Contact_No_ equals c.Company_No_


                        join sa in db.Sales_Header on cbr.No_ equals sa.Sell_to_Customer_No_

                        join px in db.PX2 on c.E_Mail equals px.Email_ID


                        where c.E_Mail == Mail.ToLower()

                        select new

                        {

                            Mail = c.E_Mail,

                            pass = px.PS,


                        };


            var user = query.FirstOrDefault();

            var CheckPass = PasswordSecurity.PasswordStorage.VerifyPassword(pass, user.pass);


            if (user != null && CheckPass) //Checkpassword

            {


                Session["Email"] = user.Mail.ToString();


            }


     else {


                // ??

         }


            return Json(user, JsonRequestBehavior.AllowGet);

        }



    }

JavaScript:


<script>


    $(document).ready(function () {


        $("#login").click(function (e) {


            var email = $("input[name=Mail]").val();

            var password = $("input[name=pass]").val();

            e.preventDefault();



            $.ajax({


                type: "POST",

                dataType: "json",

                url: '@Url.Action("Login", "Account")',

                data: { Mail: email, pass: password },

                success: function (status) {



                    if (status) {


                        window.location.href = "/Account/Index";


                    }



                }


            });


        });

    });


</script>


智慧大石
浏览 260回答 3
3回答

江户川乱折腾

看看这个 jquery 教程。我个人会使用 Fail 和 Done 回调方法。修改您的 c# 控制器以返回不同的 HTTP 状态代码。当他们传递一个好的用户名和密码时使用 HTTP 200。当他们传递错误的密码时使用 HTTP 400 这应该会触发 Fail() 回调并允许您警告失败。https://learn.jquery.com/ajax/jquery-ajax-methods/// Using the core $.ajax() method$.ajax({&nbsp; &nbsp; // The URL for the request&nbsp; &nbsp; url: "post.php",&nbsp; &nbsp; // The data to send (will be converted to a query string)&nbsp; &nbsp; data: {&nbsp; &nbsp; &nbsp; &nbsp; id: 123&nbsp; &nbsp; },&nbsp; &nbsp; // Whether this is a POST or GET request&nbsp; &nbsp; type: "GET",&nbsp; &nbsp; // The type of data we expect back&nbsp; &nbsp; dataType : "json",})&nbsp; // Code to run if the request succeeds (is done);&nbsp; // The response is passed to the function&nbsp; .done(function( json ) {&nbsp; &nbsp; &nbsp;$( "<h1>" ).text( json.title ).appendTo( "body" );&nbsp; &nbsp; &nbsp;$( "<div class=\"content\">").html( json.html ).appendTo( "body" );&nbsp; })&nbsp; // Code to run if the request fails; the raw request and&nbsp; // status codes are passed to the function&nbsp; .fail(function( xhr, status, errorThrown )** {&nbsp; &nbsp; alert( "Sorry, there was a problem!" );&nbsp; &nbsp; console.log( "Error: " + errorThrown );&nbsp; &nbsp; console.log( "Status: " + status );&nbsp; &nbsp; console.dir( xhr );&nbsp; })&nbsp; // Code to run regardless of success or failure;&nbsp; .always(function( xhr, status ) {&nbsp; &nbsp; alert( "The request is complete!" );&nbsp; });

Smart猫小萌

这就是我最终存档如何返回无效密码错误消息的方式,也许它可以在当天帮助某人:)我创建了一个enum来保存 MessageType 的值:&nbsp; public enum MessageType&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Valid,&nbsp; &nbsp; &nbsp; &nbsp; InvalidEmail,&nbsp; &nbsp; &nbsp; &nbsp; InvalidUerNameAndPass,&nbsp; &nbsp; }然后我更改我的控制器以获得不同的 MessageType:&nbsp; &nbsp; public JsonResult Login(string Mail, string pass)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; MessageType messageType = MessageType.InvalidEmail;&nbsp; &nbsp; &nbsp; &nbsp; using (DbNamesapce db = new DbNamesapce())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var query = // do Join&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; select new&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Select Something&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var user = query.FirstOrDefault();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (user == null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Json(new { messageType = MessageType.InvalidEmail }, JsonRequestBehavior.AllowGet);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (user != null && CheckPass)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messageType = MessageType.Valid;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messageType = MessageType.InvalidUerNameAndPass;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Json(new { messageType = messageType }, JsonRequestBehavior.AllowGet);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }我将脚本更改为:<script>&nbsp; &nbsp; $(document).ready(function () {&nbsp; &nbsp; &nbsp; &nbsp; $("#login").click(function (e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var email = $("input[name=Mail]").val();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var password = $("input[name=pass]").val();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: '@Url.Action("Login", "Account")',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: { Mail: email, pass: password },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function (response) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; switch ($.trim(response.messageType))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case '@Convert.ToInt32(YourNAmeSpace.Models.MessageType.Valid)':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("Valid");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case '@Convert.ToInt32(YourNAmeSpace.Models.MessageType.InvalidEmail)':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;alert("InvalidUerNameAndPass");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case '@Convert.ToInt32(YourNAmeSpace.Models.MessageType.InvalidUerNameAndPass)':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("InvalidUerNameAndPass");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });</script>

慕丝7291255

正常的做法是将响应状态设置为 401 并省略通常的数据负载,该数据负载将与成功响应一起发送。然后由客户端代码来识别错误状态并做出适当的响应(例如,可能通过显示警报并保留在名称/密码表单上);此客户端行为将在$.ajax调用中指定。
打开App,查看更多内容
随时随地看视频慕课网APP