一:首先创建项目,搭建三层这些就不多说了
二:页面代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="~/assets/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="~/assets/css/font-awesome.min.css" />
<link rel="stylesheet" href="~/assets/css/ace.min.css" />
<link rel="stylesheet" href="~/assets/css/ace-rtl.min.css" />
<link rel="stylesheet" href="~/assets/css/ace-skins.min.css" />
<link rel="stylesheet" href="~/css/style.css" />
<script src="~/js/jquery-1.9.1.min.js"></script>
<script src="~/assets/layer/layer.js" type="text/javascript"></script>
<title>登录</title>
</head>
<body class="login-layout Reg_log_style">
<div class="logintop">
<span>欢迎后台管理界面平台</span>
<ul>
<li><a href="#">返回首页</a></li>
<li><a href="#">帮助</a></li>
<li><a href="#">关于</a></li>
</ul>
</div>
<div class="loginbody">
<div class="login-container">
<div class="center">
<img src="~/images/logo1.png" />
</div>
<div class="space-6"></div>
<div class="position-relative">
<div id="login-box" class="login-box widget-box no-border visible">
<div class="widget-body">
<div class="widget-main">
<h4 class="header blue lighter bigger">
<i class="icon-coffee green"></i>
管理员登录
</h4>
<div class="login_icon"><img src="~/images/login.png" /></div>
<form class="">
<fieldset>
<ul>
<li class="frame_style form_error"><label class="user_icon"></label><input name="用户名" type="text" id="username" /><i>用户名</i></li>
<li class="frame_style form_error"><label class="password_icon"></label><input name="密码" type="password" id="userpwd" /><i>密码</i></li>
<li class="frame_style form_error">
<label class="Codes_icon"></label>
<input name="验证码" type="text" id="Codes_text" value="" />
<i>验证码</i>
<div class="Codes_region" >
@*<span width="80" height="40" onclick="createCode(4)" id="checkloing"></span>*@
<canvas width="80" height="40" id="verifyCanvas"></canvas>
<img id="code_img" />
<input id="code" value="" type="hidden" />
</div>
</li>
</ul>
<div class="space"></div>
<div class="clearfix">
<label class="inline">
<input type="checkbox" class="ace" />
<span class="lbl">保存密码</span>
</label>
<button type="button" class="width-35 pull-right btn btn-sm btn-primary" id="login_btn">
<i class="icon-key"></i>
登录
</button>
</div>
<div class="space-4"></div>
</fieldset>
</form>
<div class="social-or-login center">
<span class="bigger-110">通知</span>
</div>
<div class="social-login center">
本网站系统不再对IE11以下浏览器支持,请见谅。
</div>
</div><!-- /widget-main -->
<div class="toolbar clearfix">
</div>
</div><!-- /widget-body -->
</div><!-- /login-box -->
</div><!-- /position-relative -->
</div>
</div>
</body>
</html>
<script src="~/Scripts/Admin/login.js" type="text/javascript"></script>
三:js代码:
var nums = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
];
var str = '';
var verVal = drawCode();
// 绘制验证码
function drawCode(str) {
var canvas = document.getElementById("verifyCanvas"); //获取HTML端画布
var context = canvas.getContext("2d"); //获取画布2D上下文
context.fillStyle = "cornflowerblue"; //画布填充色
context.fillRect(0, 0, canvas.width, canvas.height); //清空画布
context.fillStyle = "white"; //设置字体颜色
context.font = "25px Arial"; //设置字体
var rand = new Array();
var x = new Array();
var y = new Array();
for (var i = 0; i < 4; i++) {
rand.push(rand[i]);
rand[i] = nums[Math.floor(Math.random() * nums.length)]
x[i] = i * 15 + 10;
y[i] = Math.random() * 20 + 20;
context.fillText(rand[i], x[i], y[i]);
}
str = rand.join('').toUpperCase();
$("#code").val(str);
//画3条随机线
for (var i = 0; i < 3; i++) {
drawline(canvas, context);
}
// 画30个随机点
for (var i = 0; i < 30; i++) {
drawDot(canvas, context);
}
convertCanvasToImage(canvas);
return str;
}
// 随机线
function drawline(canvas, context) {
context.moveTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height)); //随机线的起点x坐标是画布x坐标0位置,y坐标是画布高度的随机数
context.lineTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height)); //随机线的终点x坐标是画布宽度,y坐标是画布高度的随机数
context.lineWidth = 0.5; //随机线宽
context.strokeStyle = 'rgba(50,50,50,0.3)'; //随机线描边属性
context.stroke(); //描边,即起点描到终点
}
// 随机点(所谓画点其实就是画1px像素的线,方法不再赘述)
function drawDot(canvas, context) {
var px = Math.floor(Math.random() * canvas.width);
var py = Math.floor(Math.random() * canvas.height);
context.moveTo(px, py);
context.lineTo(px + 1, py + 1);
context.lineWidth = 0.2;
context.stroke();
}
// 绘制图片
function convertCanvasToImage(canvas) {
document.getElementById("verifyCanvas").style.display = "none";
var image = document.getElementById("code_img");
image.src = canvas.toDataURL("image/png");
return image;
}
// 点击图片刷新
document.getElementById('code_img').onclick = function () {
resetCode();
}
function resetCode() {
$('#verifyCanvas').remove();
$('#code_img').before('<canvas width="80" height="40" id="verifyCanvas"></canvas>')
verVal = drawCode();
}
//点击登录js
$("#login_btn").click(function(){
var num = 0;
var str = "";
$("input[type$='text'],input[type$='password']").each(function (n) {
if ($(this).val() === "") {
layer.alert(str += "" + $(this).attr("name") + "不能为空!\r\n", {
title: '提示框',
icon: 0
});
num++;
return false;
}
});
if (num > 0) { return false; }
else {
//登录方法获取拼接数据
var data = {};
data.Name = $("#username").val();
data.Password = $("#userpwd").val();
var isChecked = $(".ace").is(':checked');
var Codes_text = $("#Codes_text").val();
var code = $("#code").val()
if (Codes_text.toUpperCase() != code) {
layer.msg("验证码不正确!!", { time: 2000 }, function () {
resetCode();
})
return;
}
$.ajax({
url: "/Home/ButLogin?isChecked=" + isChecked,
type: "Post",
data: data,
success: function (data) {
if (data.Success) {
layer.alert('登录成功!', {
title: '提示框',
icon: 1
});
window.location.href = "/Home/Index";
layer.close(index);
} else {
layer.alert('登录失败!', {
title: '提示框',
icon: 0
});
layer.close(index);
}
},
error: function (data) {
$.messager.alert('错误', data.msg);
}
});
}
});
//页面加载js
$(function () {
$("input[type='text'],input[type='password']").blur(function () {
var $el = $(this);
var $parent = $el.parent();
$parent.attr('class', 'frame_style').removeClass(' form_error');
if ($el.val() === '') {
$parent.attr('class', 'frame_style').addClass(' form_error');
}
});
$("input[type='text'],input[type='password']").focus(function () {
var $el = $(this);
var $parent = $el.parent();
$parent.attr('class', 'frame_style').removeClass(' form_errors');
if ($el.val() === '') {
$parent.attr('class', 'frame_style').addClass(' form_errors');
} else {
$parent.attr('class', 'frame_style').removeClass(' form_errors');
}
});
});
三:后台代码
/// <summary>
/// 登录页面
/// </summary>
/// <returns></returns>
public ActionResult Login()
{
//如果session在的话直接跳转到主页
if (AdminContext.context.adminInfo != null)
{
return RedirectToAction("Index", "Home");
}
//获取cookie
var cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
//如果cookie存在的话
if (cookie != null)
{
//获取存在的cookie
var ticket = FormsAuthentication.Decrypt(cookie.Value);
string userData = ticket.UserData;
//如果存在cookie数据
if (!string.IsNullOrEmpty(userData))
{
//创建管理员信息对象将cookie的数据赋值给管理员对象
AdminUser adminUser = new AdminUser();
adminUser.Id = Convert.ToInt32(userData.Split('#')[0]);
adminUser.Name = userData.Split('#')[1];
//存储在session里面
AdminContext.context.adminInfo = adminUser;
//跳转到主页
return RedirectToAction("Index", "Home");
}
}
return View();
}
/// <summary>
/// 登录功能
/// </summary>
/// <param name="adminInfo"></param>
/// <param name="isChecked"></param>
/// <returns></returns>
public JsonResult ButLogin(AdminUser adminUser, bool isChecked)
{
//创建一个操作结果对象
OperateResult operateResult = new OperateResult();
//调用业务层登录方法
AdminUser result = new AdminUser();
if (service.Exists(a => a.Name == adminUser.Name && a.Password == adminUser.Password))
{
result = service.Query(a => a.Name == adminUser.Name && a.Password == adminUser.Password);
result.LastLoginTime = DateTime.Now;
result.LastLoginIP = ObtainIP.GetLocalIP();
service.Update(result);
}
//如果返回了对象说明登录成功
if (result != null && result.Enabled==true)
{
//返回成功
operateResult.Success = true;
//存进session
AdminContext.context.adminInfo= result;
//如果记住密码
if (isChecked)
{
//拼接要存的管理员id和登录名称
string userData = result.Id + "#" + result.Name;
//数据放入ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, adminUser.Name, DateTime.Now, DateTime.Now.AddMinutes(60), false, userData);
//数据加密
string enyTicket = FormsAuthentication.Encrypt(ticket);
//创建cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, enyTicket);
//写入cookie
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
}
return Json(operateResult);
}