1.创建数据库
CREATE DATABASE Permission; --创建数据库
CREATE TABLE [dbo].[AdminUser](
[Id] [int] IDENTITY(1,1) NOT NULL, --主键ID,自增
[Name] [varchar](50) NULL, --登录名
[Password] [varchar](36) NULL, --密码
[Email] [varchar](200) NULL --电子邮箱
)
2.搭建MVC框架
步骤:①实体类——②数据访问层——③业务逻辑层——④UI表现层
3.实体类
使用NuGet包添加引用 EntityFramework
新建项或者新建类找到ADO.NET实体数据模型,点击后按照步骤选择,如下图。
以上这样就完成了。。。
接下来再创建一个Operate验证类(用于判断):
public class Operate
{
public bool Success { get; set; }
}
4.数据访问层
使用NuGet包添加引用 EntityFramework
使用类库中的EF 6.x DbContext生成器生成数据访问层
在自动生成的Model1.Context.tt中删除里面所有代码,添加下面代码
<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#><#@
output extension=".cs"#>
<#
MetadataLoader loader = new MetadataLoader(this);
string inputFile = @"..\\YouYi.Admin.Mode\Model1.edmx"; //地址修改成自己的实体类的路径
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YouYi.Admin.Mode; //修改成自己的实体类的命名空间
namespace YouYi.Admin.DAL //修改成自己的数据访问层的命名空间
{
<#
foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,PermissionEntities>
//BaseRepository、PermissionEntities下面代码说明
{
}
<#}#>
}
PermissionEntities:这个是从实体类获取
DbContextFactory:用于查询数据库与对数据组合的更改
public class DbContextFactory<TS> where TS : DbContext, new()
{
public static DbContext GetCurrentDbContext()
{
var dbContext = CallContext.GetData(typeof(TS).Name) as DbContext;
if (dbContext != null)
{
return dbContext;
}
else
{
dbContext = new TS();
CallContext.SetData(typeof(TS).Name, dbContext);
return dbContext;
}
}
}
BaseRepository:在数据访问层中添加一个基类(用于增删改查)
public class BaseRepository<T, TS> where T : class
where TS : DbContext, new()
{
private DbContext db = DbContextFactory<TS>.GetCurrentDbContext();
//添加单条记录
public bool Add(T entily)
{
db.Set<T>().Add(entily);
return db.SaveChanges() > 0;
}
//添加多条记录
public bool AddList(List<T> entily)
{
db.Set<T>().AddRange(entily);
return db.SaveChanges() > 0;
}
//删除
public bool DELETE(T entily)
{
db.Entry(entily).State = EntityState.Deleted;
return db.SaveChanges() > 0;
}
//删除多个
public bool BDELETE(List<T> entiles)
{
db.Set<T>().RemoveRange(entiles);
return db.SaveChanges() > 0;
}
//根据id删除
public bool BatchDELETE(params int[] entiles)
{
foreach (var id in entiles)
{
var entity = db.Set<T>().Find(id);
if (entity != null)
{
db.Set<T>().Remove(entity);
}
}
return db.SaveChanges() > 0;
}
//修改
public bool Update(T entily)
{
db.Entry(entily).State = EntityState.Modified;
return db.SaveChanges() > 0;
}
//查询一个集合
public List<T> QueryList(Expression<Func<T, bool>> lambdaExpression)
{
return db.Set<T>().Where(lambdaExpression).ToList();
}
//查询一个对象,如果没有返回null
public T Query(Expression<Func<T, bool>> lambdaExpression)
{
return db.Set<T>().SingleOrDefault(lambdaExpression);
}
public bool Exists(Expression<Func<T, bool>> lambdaExpression)
{
return db.Set<T>().Any(lambdaExpression);
}
//分页查询
public List<T> QuerypageList<S>(int pageIndex, int pageSize, Expression<Func<T, bool>> wheredma, Expression<Func<T, S>> orderbyLamba, out int count, bool isAc = true)
{
count = db.Set<T>().Where(wheredma).Count();
if (!isAc)
{
return db.Set<T>().Where(wheredma).OrderByDescending(orderbyLamba).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
else
{
return db.Set<T>().Where(wheredma).OrderBy(orderbyLamba).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
}
}
5.业务逻辑层
使用NuGet包添加引用 EntityFramework
添加BaseService基类,用于继承调用数据访问层BaseRepository里的所有方法
public class BaseService<T> where T : class
{
private BaseRepository<T, PermissionEntities1> baseRepository = new BaseRepository<T, PermissionEntities1>();
//添加单条记录
public virtual bool Add(T entily)
{
return baseRepository.Add(entily);
}
//添加多条记录
public virtual bool AddList(List<T> entily)
{
return baseRepository.AddList(entily);
}
//删除
public virtual bool DELETE(T entily)
{
return baseRepository.DELETE(entily);
}
//删除多个
public virtual bool BDELETE(List<T> entiles)
{
return baseRepository.BDELETE(entiles);
}
//根据id删除
public bool BatchDELETE(params int[] entiles)
{
return baseRepository.BatchDELETE(entiles);
}
//修改
public virtual bool Update(T entily)
{
return baseRepository.Update(entily);
}
//查询一个集合
public virtual List<T> QueryList(Expression<Func<T, bool>> lambdaExpression)
{
return baseRepository.QueryList(lambdaExpression);
}
//查询一个对象,如果没有返回null
public virtual T Query(Expression<Func<T, bool>> lambdaExpression)
{
return baseRepository.Query(lambdaExpression);
}
public virtual bool Exists(Expression<Func<T, bool>> lambdaExpression)
{
return baseRepository.Exists(lambdaExpression);
}
//分页查询
public virtual List<T> QuerypageList<S>(int pageIndex, int pageSize, Expression<Func<T, bool>> wheredma, Expression<Func<T, S>> orderbyLamba, out int count, bool isAc = true)
{
return baseRepository.QuerypageList(pageIndex, pageSize, wheredma, orderbyLamba, out count, isAc);
}
}
创建一个AdminUserService类,用于登录,主页面欢迎和管理员的增删改操作,继承BaseService类
public class AdminUserService : BaseService<AdminUser>
{
//因为是单表操作,没有太复杂的操作,就直接为空就好了
}
6.IU表现层
使用NuGet包添加引用 EntityFramework
在Models中创建一个上下文AdminContext的类:
/// <summary>
/// 管理员的上下文
/// </summary>
public class AdminContext
{
/// <summary>
/// 会话的key
/// </summary>
private string SessionKey = "ADMIN_KEY";
/// <summary>
/// 静态的上下文
/// </summary>
public static AdminContext adminContext = new AdminContext();
/// <summary>
///会话状态
/// </summary>
public HttpSessionState httpSessionState => HttpContext.Current.Session;
/// <summary>
/// 用户对象
/// </summary>
public AdminUser adminInfo
{
get
{
return httpSessionState[SessionKey] as AdminUser;
}
set
{
httpSessionState[SessionKey] = value;
}
}
}
在view--Home下添加三个页面,我这边分别是Login登录页,Index主页面,User功能页(增删改查),并在控制器Home里面创建方法为页面跳转。
Login页面:
<script type="text/javascript">
//登录
$("#den").on('click', function () { //登录的按钮
var flag = false;
if ($("#checkpwd").is(":Checked")) { flag = true; } //这是记住密码的单选框
var datas = {}; //创建对象
datas.Name = $("#name").val(); //获取登录名
datas.Password = $("#pwd").val(); //获取密码
//用ajax上传数据,data是数据,url是控制器
$.ajax({
data: datas,
type: "post",
url: "/Login/GetLogin?check=" + flag,
success: function (operate) {
if (operate.Success) {
alert("登录成功");
window.location.href = "/Home/Index";
} else {
alert("登录失败");
}
}
})
})
</script>
创建Login的控制器,并创建登录所需要的GetLogin方法
public class LoginController : Controller
{
private AdminUserService adminInfoService = new AdminUserService();
#region 登录
public JsonResult GetLogin(AdminUser adminUser, bool check)
{
Operate operate = new Operate();
AdminUser adminUsers = new AdminUser();
Expression<Func<AdminUser, bool>> lambdaExpression = a => a.Name == adminUser.Name && a.Password == adminUser.Password;
adminUsers = adminInfoService.Query(lambdaExpression);
operate.Success = adminUsers != null;
if (adminUsers != null)
{
operate.Success = true;
//存储session值
AdminContext.adminContext.adminInfo = adminUsers;
//如果选中保存密码则存储cookie
if (check)
{
//存储cookie
//创建一个Cookie对象
HttpCookie httpCookie = new HttpCookie("CookieName");
//设置Cookie的值
httpCookie.Values.Add("Name", adminUsers.Name);
httpCookie.Values.Add("Password", adminUsers.Password);
httpCookie.Values.Add("DateTime", DateTime.Now.AddDays(7).ToString("yyyy-MM-dd HH:mm:ss"));
//设置Cookie的过期时间
httpCookie.Expires = DateTime.Now.AddDays(7);
System.Web.HttpContext.Current.Response.Cookies.Add(httpCookie);
}
}
return Json(operate);
}
#endregion
记住密码的功能,在上面GetLogin方法已经存了cookie,所以在下次登录的时候直接调用cookie就好了
public ActionResult Login()
{
//取出Cookie保存的信息
HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get("CookieName");
if (cookie != null)
{
string name = cookie["Name"];//等同于string name = cookie.Values.Get("UserName");
string pwd = cookie["Password"];
if (name != null && pwd != null && DateTime.Parse(cookie["DateTime"]) != null && DateTime.Now < DateTime.Parse(cookie["DateTime"]))
{
//将Cookie中的值赋给上下文session 使其在不登录时页面也能够显示
AdminContext.adminContext.adminInfo = new AdminUser()
{
Name = name,
Password = pwd
};
return Redirect("/Home/Index");
}
}
return View();
}
主页面Index欢迎:
是调用GetLogin方法存的cookie,拿出名字即可
@*引入上下文AdminContext的命名空间*@
@using YouYi.Admin.Web.Models;
@{
var admin = AdminContext.adminContext.adminInfo;
}
@*body下*@
欢迎光临 @if (admin != null) {@admin.Name}
在UI表现层Model下添加PageListResult类(用于分页操作,显示列表)
public class PageListResult<T>
{
public int code { get; set; }
public string msg { get; set; }
public int count { get; set; }
public List<T> data { get; set; }
}
User功能页(增删改查)
页面:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<!--[if lt IE 9]>
<script type="text/javascript" src="lib/html5shiv.js"></script>
<script type="text/javascript" src="lib/respond.min.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="~/static/h-ui/css/H-ui.min.css" />
<link rel="stylesheet" type="text/css" href="~/static/h-ui.admin/css/H-ui.admin.css" />
<link rel="stylesheet" type="text/css" href="~/lib/Hui-iconfont/1.0.8/iconfont.css" />
<link rel="stylesheet" type="text/css" href="~/static/h-ui.admin/skin/default/skin.css" id="skin" />
<link rel="stylesheet" type="text/css" href="~/static/h-ui.admin/css/style.css" />
<link rel="stylesheet" href="~/layui/css/layui.css" />
<!--[if IE 6]>
<script type="text/javascript" src="lib/DD_belatedPNG_0.0.8a-min.js" ></script>
<script>DD_belatedPNG.fix('*');</script>
<![endif]-->
<title>用户管理</title>
</head>
<body>
<nav class="breadcrumb"><i class="Hui-iconfont"></i> 首页 <span class="c-gray en">></span> 用户中心 <span class="c-gray en">></span> 用户管理 <a class="btn btn-success radius r" style="line-height:1.6em;margin-top:3px" href="javascript:location.replace(location.href);" title="刷新"><i class="Hui-iconfont"></i></a></nav>
<div class="pd-20">
<input type="text" id="UserName" class="input-text" style="width:250px" placeholder="输入会员名称" name=""><button id="getLike" type="submit" class="btn btn-success" id="" name=""><i class="icon-search"></i> 搜用户</button>
</div>
<table class="layui-hide" id="test" lay-filter="demo"></table>
<script id="barDemo" type="text/html">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<div class="cl pd-5 bg-1 bk-gray mt-20">
<span class="l_f">
<a href="javascript:ovid()" id="Competence_add" class="btn btn-warning" title="添加用户"><i class="fa fa-plus"></i> 添加用户</a>
</span>
</div>
<div id="pageNav" class="pageNav">123</div>
<div id="Competence_add_style" style="display:none">
<div class="Competence_add_style">
<div class="form-group">
<label class="col-sm-2 control-label no-padding-right" for="form-field-1"> 名称 </label>
<div class="col-sm-9"><input type="text" id="Name" placeholder="" name="名称" class="col-xs-10 col-sm-5" /></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label no-padding-right" for="form-field-1"> 密码 </label>
<div class="col-sm-9"><input type="text" id="Password" placeholder="" name="密码" class="col-xs-10 col-sm-5" /></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label no-padding-right" for="form-field-1"> 邮箱 </label>
<div class="col-sm-9"><input type="text" id="Email" placeholder="" name="邮箱" class="col-xs-10 col-sm-5" /></div>
</div>
</div>
</div>
<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="~/lib/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="~/lib/layer/2.4/layer.js"></script>
<script type="text/javascript" src="~/static/h-ui/js/H-ui.min.js"></script>
<script type="text/javascript" src="~/static/h-ui.admin/js/H-ui.admin.js"></script>
<script src="~/layui/layui.js" type="text/javascript"></script>
<!--/_footer 作为公共模版分离出去-->
<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="~/lib/My97DatePicker/4.8/WdatePicker.js"></script>
<script type="text/javascript" src="~/lib/datatables/1.10.0/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="~/lib/laypage/1.2/laypage.js"></script>
</body>
</html>
<script type="text/javascript">
layui.use('table', function () {
var table = layui.table
, form = layui.form; //启用
table.render({
elem: '#test'
, url: '/User/GetAdminUserPageList'
, cellMinWidth: 80
, cols: [[
{ type: 'checkbox' }
, { field: 'Id', width: 180, align: 'center', title: 'Id', sort: true }
, { field: 'Name', width: 180, align: 'center', title: '用户名' }
, { field: 'Password', width: 180, align: 'center', title: '密码' }
, { field: 'Email', width: 180, align: 'center', title: '邮箱' }
, { fixed: 'right', title: '操作', width: 208, align: 'center', toolbar: '#barDemo' }
]]
, page: true
, id: 'testReload'
});
$("#getLike").click(function () {
var table = layui.table;
//获取页面的查询条件
var UserName = $("#UserName").val();
//上述方qq1法等价于
table.reload('testReload', {
where: { //设定异步数据接口的额外参数,任意设
UserName: UserName,
//…
}
});
});
table.on('tool(demo)', function (obj) {
var AdminUser = obj.data;
var ID = AdminUser.Id;
if (obj.event === 'del') {
//删除
layer.confirm('确定删除吗?', function (index) {
$.ajax({
url: "/User/DelAdminUser?Id=" + ID,
type: "Post",
success: function (data) {
if (data.Success) {
layer.msg('删除成功!', {
title: '提示框',
icon: 1,
time: 2000
}, function () {
location.reload();//刷新页面
layer.close(index);
});
}
else {
layer.msg('删除失败!', {
title: '提示框',
icon: 1,
time: 2000
});
}
}
});
});
}
else if (obj.event === 'edit') {
$("#ID").val(AdminUser.Id);
$("#Name").val(AdminUser.Name);
$("#Password").val(AdminUser.Password);
$("#Email").val(AdminUser.Email);
layer.open({
type: 1,
title: '修改菜单',
maxmin: true,
shadeClose: false,
area: ['800px', ''],
content: $('#Competence_add_style'),
btn: ['提交', '取消'],
yes: function (index, layero) {
var num = 0;
var str = "";
$(".col-sm-9 input[type$='text'],#form_textarea").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 user = {};
user.Id = ID;
user.Name = $("#Name").val();
user.Password = $("#Password").val();
user.Email = $("#Email").val();
$.ajax({
url: "/User/AddUpdateAdminUser",
type: "post",
data: user,
success: function (result) {
if (result.Success) {
layer.msg("修改成功");
location.reload();//刷新页面
}
else {
layer.msg("修改失败", { icon: 0, time: 3000 });
}
}
})
}
}
})
}
})
});
//添加
$('#Competence_add').on('click', function () {
layer.open({
type: 1,
title: '添加菜单',
maxmin: true,
shadeClose: false,
area: ['800px', ''],
content: $('#Competence_add_style'),
btn: ['提交', '取消'],
yes: function (index, layero) {
var num = 0;
var str = "";
$(".col-sm-9 input[type$='text'],#form_textarea").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 user = {};
user.Name = $("#Name").val();
user.Password = $("#Password").val();
user.Email = $("#Email").val();
$.ajax({
url: "/User/AddUpdateAdminUser",
type: "post",
data: user,
success: function (result) {
if (result.Success) {
layer.msg("添加成功");
location.reload();//刷新页面
}
else {
layer.msg("添加失败", { icon: 0, time: 3000 });
}
}
})
}
}
})
})
</script>
添加User控制器
public class UserController : Controller
{
private AdminUserService adminUserService = new AdminUserService();
#region 列表-分页查询
public ActionResult GetAdminUserPageList(int page, int limit, string UserName)
{
PageListResult<AdminUser> pageListResult = new PageListResult<AdminUser>();
pageListResult.code = 0;
pageListResult.msg = string.Empty;
int count = 0;
Expression<Func<AdminUser, bool>> Wherelambda = c => true;
if (!string.IsNullOrEmpty(UserName))
{
Wherelambda = a => a.Name.Contains(UserName);
}
Expression<Func<AdminUser, int>> OrderBylambda = c => c.Id;
pageListResult.data = adminUserService.QuerypageList(page, limit, Wherelambda, OrderBylambda, out count);
return Json(pageListResult, JsonRequestBehavior.AllowGet);
}
#endregion
#region 删除
public ActionResult DelAdminUser(AdminUser adminUser)
{
Operate operate = new Operate();
operate.Success = adminUserService.DELETE(adminUser);
return Json(operate);
}
#endregion
#region 添加与修改
public ActionResult AddUpdateAdminUser(AdminUser adminUser)
{
Operate operate = new Operate();
if (adminUser.Id != 0)
{
//修改
operate.Success = adminUserService.Update(adminUser);
}
else
{
//添加
operate.Success = adminUserService.Add(adminUser);
}
return Json(operate);
}
#endregion
}
至此,功能都实现了。