1.新建数据库
USE [Permission]
GO
/****** Object: Table [dbo].[AdminUser] Script Date: 10/16/2019 08:53:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AdminUser](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Password] [varchar](36) NULL,
[Email] [varchar](200) NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
2.搭建EF框架
3.创建实体类和数据库连接,自动生成实体类
在引用中使用NuGet包添加引用 EntityFramework
在实体类中手动添加一个类 (判断值)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Admin.Mode
{
public class Operate
{
public bool Success { get; set; }
}
}
4.数据访问层
在引用中使用NuGet包添加引用 EntityFramework
然后把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 = @"..\\Admin.Mode\Model1.edmx";
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Admin.Mode;
namespace Admin.Mode
{
<#
foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,PermissionEntities>
{
}
<#}#>
}
并且创建BaseRepository.cs基类
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Admin.ADL
{
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.cs
using Admin.ADL;
using Admin.Mode;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Admin.BLL
{
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);
}
}
}
在业务逻辑层创建AdminInfoService类
using Admin.ADL;
using Admin.Mode;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Admin.BLL
{
public class AdminInfoService : BaseService<AdminUser>, IDenpendecy
{
}
}
6.UI层
在引用中使用NuGet包添加引用 EntityFramework
在UI层建立一个上下文AdminContext类
using Admin.Mode;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace Admin.Models
{
/// <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;
}
}
}
}
然后去登录页面写方法
//登录
$("#den").on('click', function () {
var flag = false;
if ($("#checkpwd").is(":Checked")) { flag = true; }
var AdminInfo = {};
AdminInfo.Name = $("#name").val();
AdminInfo.Password = $("#pwd").val();
$.ajax({
data: AdminInfo,
type: "post",
url: "/Login/Login?check=" + flag,
success: function (operate) {
if (operate.Success) {
alert("登录成功");
window.location.href = "/Home/Index";
} else {
alert("登录失败");
}
}
})
})
在控制台写方法,存Cookie
using Admin.BLL;
using Admin.Mode;
using Admin.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace Admin.Controllers
{
public class LoginController : Controller
{
private AdminInfoService adminInfoService = new AdminInfoService();
#region 登录
public JsonResult Login(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
}
}
在Home控制器中写方法
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"];
//DateTime time = DateTime.Parse(cookie["DateTime"]);
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();
}
页面欢迎
//顶部引用
@{
Layout = null;
}
@using Admin.Mode;
@using Admin.Models;
@{
ViewBag.Title = "Home Page";
var admin = AdminContext.adminContext.adminInfo;
}
//欢迎
<a href="#" class="dropDown_A">
欢迎光临 @if (admin != null)
{@admin.Name}
增删改查功能
控制器代码
using Admin.BLL;
using Admin.Mode;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
namespace Admin.Controllers
{
public class UserController : Controller
{
public UserService user = new UserService();
#region 显示查询
public ActionResult Display(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 = user.QuerypageList(page, limit, Wherelambda, OrderBylambda, out count);
return Json(pageListResult, JsonRequestBehavior.AllowGet);
}
#endregion
#region 删除
public ActionResult Delete(AdminUser adminUser)
{
Operate operate = new Operate();
operate.Success = user.DELETE(adminUser);
return Json(operate);
}
#endregion
#region 添加和修改
public ActionResult Addhh(AdminUser adminUser)
{
Operate operate = new Operate();
if (adminUser.Id != 0)
{
operate.Success = user.Update(adminUser);
}
else
{
operate.Success = user.Add(adminUser);
}
return Json(operate);
}
#endregion
}
}
页面代码
layui.use('table', function () {
var table = layui.table
, form = layui.form; //启用
table.render({
elem: '#test'
, url: '/User/Display/'
, 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/Delete?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/Addhh",
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/Addhh",
type: "post",
data: user,
success: function (result) {
if (result.Success) {
layer.msg("添加成功");
location.reload();//刷新页面
}
else {
layer.msg("添加失败", { icon: 0, time: 3000 });
}
}
})
}
}
})
})
过滤器
在控制器建一个文件夹,创建一个ActionAttribute 行为过滤器的类
using Admin.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Admin.Attributes
{
public class ActionAttribute : ActionFilterAttribute //行为过滤器
{
/// <summary>
/// 调用控制器对应的Action方法之后的操作
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (AdminContext.adminContext.adminInfo != null)
{
//获取用户名
string username = AdminContext.adminContext.adminInfo.Name;
string controller = filterContext.RouteData.Values["Controller"].ToString();
string action = filterContext.RouteData.Values["Action"].ToString();
//获取系统的日志
string msg = $"时间:{DateTime.Now},用户名:{username},已完成控制器:{controller},页面:{action}";
//获取文件路径
string path = "D:\\lj.txt";
File.AppendAllText(path, msg);
}
}
/// <summary>
/// 调用控制器对应的Action方法之前的操作
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (AdminContext.adminContext.adminInfo!=null)
{
//获取用户名
string username = AdminContext.adminContext.adminInfo.Name;
string controller = filterContext.RouteData.Values["Controller"].ToString();
string action = filterContext.RouteData.Values["Action"].ToString();
//获取系统的日志
string msg = $"时间:{DateTime.Now},用户名:{username},正在操作控制器:{controller},页面:{action}";
//获取文件路径
string path = "D:\\Exception.txt";
File.AppendAllText(path, msg);
}
}
/// <summary>
/// 调用控制器对应的Action方法之后页面渲染之后的操作
/// </summary>
/// <param name="filterContext"></param>
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
}
/// <summary>
/// 调用控制器对应的Action方法之后页面渲染之前的操作
/// </summary>
/// <param name="filterContext"></param>
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
}
}
}
创建一个ExceptionAttribute异常过滤器的类
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Admin.Models
{
public class ExceptionAttribute : HandleErrorAttribute //异常过滤器
{
/// <summary>
/// 系统发生异常的操作
/// </summary>
/// <param name="filterContext"></param>
public override void OnException(ExceptionContext filterContext)
{
//Exception exception = filterContext.Exception;
//string msg = exception.Message;
//获取系统的日志
string exception = filterContext.Exception.ToString();
string msg = $"时间:{DateTime.Now},系统出错:{exception}";
//获取文件路径
string path = "D:\\Exception.txt";
//如果文件不存在则创建
/*if (!File.Exists(path))
{
File.Create(path);
}*/
File.AppendAllText(path, msg);
}
}
}
创建一个PermissionAttribute权限过滤器的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Admin.Models
{
public class PermissionAttribute : AuthorizeAttribute //权限过滤器
{
/// <summary>
/// 判断认证是否通过
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//如果上下文不为空
if (AdminContext.adminContext.adminInfo != null && httpContext.Session != null)
{
return true;
}
return false;
}
/// <summary>
///认证不通过的时候所做的操作
/// </summary>
/// <param name="filterContext"></param>
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
//获取用户请求的地址
string path = filterContext.HttpContext.Request.Path;
//自定义路由跳转
Dictionary<string, object> keys = new Dictionary<string, object>();
keys.Add("Controller", "Home");
keys.Add("Action", "Login");
keys.Add("ReturnUrl", path);
var routeValue = new RouteValueDictionary(keys);
//根据指定路由跳转
filterContext.Result = new RedirectToRouteResult(routeValue);
}
}
}