ajax方式登录

写在前面

今天回来的比较早,就趁着有空,把登录的代码更新一下。上篇文章实现了ajax的注册,这篇将实现登录,实现目标,ajax登录方式,如果勾选记住我,则下次不再输入用户名密码,直接跳转到网盘界面。

代码


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="企业,网盘,企业网盘">
    <meta name="author" content="Muhammad Usman">
    <title>登录</title>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <link href="~/Content/Css/bootstrap-cerulean.min.css" rel="stylesheet" />
    <link href="~/Content/Css/charisma-app.css" rel="stylesheet" />
    <link href="~/Content/Css/jquery.noty.css" rel="stylesheet" />

    <link href="~/Content/Css/elfinder.min.css" rel="stylesheet" />
    <link href="~/Content/Css/elfinder.theme.css" rel="stylesheet" />

    <link href="~/Content/Css/jquery.iphone.toggle.css" rel="stylesheet" />
    <link href="~/Content/Css/animate.min.css" rel="stylesheet" />
    <script>
        $(function () {
            //多选框
            $("#chkRemember").click(function () {
                if (!$(this).attr("checked")) {
                    $(this).attr("checked", 'checked');
                } else {
                    $(this).removeAttr("checked");
                };
            });
            //为登录按钮注册单击事件
            $('#btnLogin').click(function () {

                $.ajax({
                    type: "post",
                    url: "/UserInfo/Login",
                    data: { userName: $("#txtUserName").val(), pwd: $("#txtPwd").val(), remember: $("#chkRemember").attr('checked') },
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                        data = JSON.parse(data);
                        if (data.code == 200) {

                        } else {
                            $("#loginMsg").html("<span style='color:red;'>"+data.msg+"</span>");
                        };

                    }, error: function (msg) {
                        alert(data);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div class="row">

        <div class="row">
            <div class="col-md-12 center login-header">
                <h2>欢迎使用 Wolfy企业网盘</h2>
            </div>
            <!--/span-->
        </div><!--/row-->
        <div class="container">
            <div class="row">
                <div class="well col-md-5 center login-box">
                    <div class="alert alert-info" id="loginMsg">
                        请使用用户名和密码登录
                    </div>

                    <fieldset>
                        <div class="input-group input-group-lg">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-user red"></i></span>
                            <input type="text" class="form-control" id="txtUserName" placeholder="用户名">
                        </div>
                        <div class="clearfix"></div><br>

                        <div class="input-group input-group-lg">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-lock red"></i></span>
                            <input type="password" class="form-control" id="txtPwd" placeholder="密码">
                        </div>
                        <div class="clearfix"></div>

                        <div class="input-prepend">
                            <label class="remember" for="chkRemember"><input type="checkbox" name="chkRemember" id="chkRemember" value="1" /> 记住我</label>
                        </div>
                        <div class="clearfix"></div>

                        <p class="center col-md-5">
                            <button type="button" class="btn btn-primary" id="btnLogin">登录</button>
                        </p><a href="/UserInfo/Register" class="right" style="float:right;">注册</a>
                    </fieldset>

                </div>
                <!--/span-->
            </div><!--/row-->
        </div><!--/fluid-row-->
    </div>
</body>
</html>

目前还是使用session来保持状态,使用在action上加特性的方式,留待以后优化。

[HttpGet]
public ActionResult Login()
{
    UserInfo userInfo = null;
    if (Request.Cookies["n"] != null && Request.Cookies["p"] != null)
    {
        string userName = Request.Cookies["n"].Value;
        string pwd = Request.Cookies["p"].Value;
        userInfo = _userInfoServiceRepository.Find(x => x.UserName == userName && x.Pwd == pwd);
        if (userInfo!=null)
        {
            if (Session["user"] == null)
            {
                Session["user"] = userInfo;
            }
            //更新最后一次登录时间
            userInfo.LoginDt = DateTime.Now;
            _userInfoServiceRepository.Update(userInfo);
            _userInfoServiceRepository.SaveChanges();
        }
      
    }
    return View();
}
/// <summary>
/// 登录
/// </summary>
/// <param name="userName"></param>
/// <param name="code"></param>
/// <returns></returns>
[HttpPost]
public JsonResult Login(string userName, string pwd, string remember)
{
    if (!_userInfoServiceRepository.Exist(userName))
    {
        return new JsonResult() { Data = "{\"code\":500,\"msg\":\"用户名不存在\"}" };
    }
    if (!string.IsNullOrEmpty(pwd))
    {
        pwd = MD5Helper.GetMD5FromString(pwd);
    }
    else
    {
        return new JsonResult() { Data = "{\"code\":500,\"msg\":\"密码不能为空\"}" };
    }
    UserInfo userInfo = _userInfoServiceRepository.Find(x => x.UserName == userName && x.Pwd == pwd);
    if (userInfo == null)
    {
        return new JsonResult() { Data = "{\"code\":500,\"msg\":\"用户名和密码不匹配\"}" };
    }
    if (!string.IsNullOrEmpty(remember) && remember.Equals("checked"))
    {
        HttpCookie nameCookie = new HttpCookie("n", userName);
        nameCookie.Expires = DateTime.Now.AddDays(7);
        //将md5串写入cookie,或者再次进行AES加密写入
        HttpCookie pwdCookie = new HttpCookie("p", pwd);
        pwdCookie.Expires = DateTime.Now.AddDays(7);
        Response.Cookies.Add(nameCookie);
        Response.Cookies.Add(pwdCookie);
    }
    //登录成功写入session
    Session["user"] = userInfo;
    //更新登录状态
    userInfo.LoginDt = DateTime.Now;
    _userInfoServiceRepository.Update(userInfo);
    _userInfoServiceRepository.SaveChanges();
    return new JsonResult() { Data = "{\"code\":200,\"msg\":\"登录成功\"}" };
}

测试

登录成功后,跳转到FileList页面。

总结

关于ajax方式登录的内容就到这里。下面将进入网盘的主页。