.NET Core6.0 MVC+layui+SqlSugar 简单增删改查

2023-12-04 16:20

本文主要是介绍.NET Core6.0 MVC+layui+SqlSugar 简单增删改查,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

HTML部分:

@{ViewData["Title"] = "用户列表";
}
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>用户列表</title><meta name="renderer" content="webkit"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><link rel="stylesheet" href="~/layui/lib/layui-v2.6.3/css/layui.css" media="all"><link rel="stylesheet" href="~/layui/css/public.css" media="all"><script src="~/layui/lib/layui-v2.6.3/layui.js" charset="utf-8"></script><script src="~/learun/js/jquery/jquery-2.2.0.min.js"></script><script>//添加用户 层function OpenAdd() {var index = layer.open({type: 1, //0 dialog 信息框 1; page 页面层;2 iframe 内联框架层;3 loading 加载层;4 tips 贴士层title: "",content: `
<table class="layui-table">
<tr><td>账号</td><td><input type="text" id="txtName" class="layui-text" /></td></tr><tr><td>类型</td><td><select id="selType" style="width:175px; height:32px;"><option value="0">普通用户</option><option value="1">管理员</option></select></td></tr>
</table>`,area: ["300px", "200px"],//弹出尺寸btn: ["保存"],btn1: function (index, layero) {AddUser();},cancel: function () {PageList(1);//刷新列表}});}//编辑用户 层function OpenEdit(id, name, type) {var index = layer.open({type: 1, //0 dialog 信息框 1; page 页面层;2 iframe 内联框架层;3 loading 加载层;4 tips 贴士层title: "",content: `
<table class="layui-table">
<tr><td>ID</td><td><span id="spanId"><span/></td></tr><tr><td>账号</td><td><input type="text" id="txtName" class="layui-text" value="" /></td></tr><tr><td>类型</td><td><select id="selType" style="width:175px; height:32px;"><option value="0">普通用户</option><option value="1">管理员</option></select></td></tr>
</table>`,area: ["500px", "250px"],//弹出尺寸success: function () {//回绑控件$("#spanId").html(id);$("#txtName").val(name);$("#selType").val(type);},btn: ["保存"],btn1: function (index, layero) {EditUser();},cancel: function () {PageList(1);//刷新列表}});}//删除用户 层function OpenDel(id, name) {layer.confirm('确定删除: ' + name + ' ?', {btn: ['确定', '取消']}, function (index, layero) {//btn1if (name.toLowerCase() != 'admin'){DelUser(id);}else{layer.msg("不可以删除 admin 账号!");}}, function (index) {//btn2PageList(1);//刷新列表});}</script></head>
<body><div class="layuimini-container" id="app"><div class="layuimini-main"><!-----查询条件-----><div class="layui-form-item"><div class="layui-inline"><label class="layui-form-label">用户名</label><div class="layui-input-inline"><input type="text" autocomplete="off" class="layui-input" id="txtUserName"></div></div><div class="layui-inline"><label class="layui-form-label">类型</label><div class="layui-input-inline"><select id="selUserType" style="width:175px; height:32px;"><option value="">全部</option><option value="0">普通用户</option><option value="1">管理员</option></select></div></div><div class="layui-inline"><button type="button" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn" onclick="PageList()"><i class="layui-icon"></i> 搜 索</button><button type="button" class="layui-btn" style="margin-left:300px;" onclick="OpenAdd()">添加新用户</button></div></div><!-----查询条件-----><!--表格--><table id="table" class="layui-table" lay-filter="table"></table><!--表格--></div></div><script type="text/html" id="templetType">{{#  if(d.type === '1'){ }}管理员{{#  } else { }}普通用户{{#  } }}</script><script type="text/html" id="tempCreateDate">{{#}}{{  d.createDate.replace('T',' ') }}{{#}}</script><script type="text/javascript">//初始化$(function () {PageList();});$(function () {$("#selUserType").change(function () {PageList();});});//查询function PageList() {var name = $("#txtUserName").val();//查询条件var type = $("#selUserType").val();layui.use(['table'], function () {var table = layui.table;table.render({elem: '#table'//对应着Table的ID, method: 'POST', url: '/User/GetUserPage'//URL为数据接口的地址, where: { //where就是ajax的data,但不包括分页条件"name": name,"type": type,}, request: {  //分页条件: page  limitpageName: 'page',    //页码的参数名称,默认:page 或者 index、pageIndexlimitName: 'size'  //每页数据量的参数名,默认:limit 或者 size、pageSize}, parseData: function (res) {return {"code": 0,//数据类型,必须的"count": res.total,//总记录数,用于分页"data": res.data,//必须的}}, cols: [[{ field: 'account', title: 'ID', hide: true }, { field: 'name', title: '姓名', sort: true }, { field: 'type', title: '类型', sort: true, templet: "#templetType" }, { field: 'createBy', title: '创建者', sort: true, }, { field: 'createDate', title: '创建日', sort: true, templet: "#tempCreateDate" }, { title: '操作', toolbar: '#barDemo' }]],page: true,//开启分页功能limit: 15,//当前每页条数limits: [15, 30, 50, 100],//每页条数集合});});}</script><script type="text/html" id="barDemo"><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><script>layui.use('table', function () {var table = layui.table;//监听工具条table.on('tool(table)', function (obj) {var data = obj.data;if (obj.event === 'edit') {OpenEdit(data.account, data.name, data.type);}if (obj.event === 'del') {OpenDel(data.account, data.name);}});});</script><script>//添加用户ajaxfunction AddUser() {var name = $("#txtName").val();var type = $("#selType").val();if (name) {$.ajax({type: "POST",url: "/User/AddUser",data: {"name": name,"type": type,},success: function (result) {if (result.success) {layer.msg('添加成功!', {icon: 1,time: 1000 //1秒关闭(如果不配置,默认是3秒)}, function () {PageList(1);layer.closeAll();});}else {layer.msg('添加失败!');}}});}else {layer.msg("请填写[账号]!");}}</script><script>function EditUser() {var account = $("#spanId").html();var name = $("#txtName").val();var type = $("#selType").val();if (account) {if (name) {$.ajax({type: "POST",url: "/User/EditUser",data: {"account": account,"name": name,"type": type,},success: function (result) {if (result.success) {layer.msg('保存成功!', {icon: 1,time: 1000 //1秒关闭(如果不配置,默认是3秒)}, function () {PageList(1);layer.closeAll();});}else {layer.msg('保存失败!');}}});}else {layer.msg("请填写[账号]!");}}}</script><script>function DelUser(id) {var account = id;if (id) {$.ajax({type: "POST",url: "/User/DelUser",data: {"account": account,},success: function (result) {if (result.success) {layer.msg('删除成功!', {icon: 1,time: 1000 //1秒关闭(如果不配置,默认是3秒)}, function () {PageList(1);layer.closeAll();});}else {layer.msg('删除失败!');}}});}else {layer.msg("删除失败!!");}}</script></body>
</html>

MVC部分:

using Microsoft.AspNetCore.Mvc;
using VoltageInvoiceBLL;
using VoltageInvoiceModel;
using VoltageInvoiceUI.Models;namespace VoltageInvoiceUI.Controllers
{public class UserController : BaseController{#region 页面public UserController(){if (string.IsNullOrWhiteSpace(LOGIN_USER_NAME) || string.IsNullOrWhiteSpace(LOGIN_USER_TYPE) || string.IsNullOrWhiteSpace(LOGIN_USER_ACCOUNT)){RedirectToAction("LogIn", "Home");//返回登录页面}}//列表页面public IActionResult Index(){return View();}#endregion#region 用户管理public IActionResult Edit(){return View();}/// <summary>/// 分页查询用户/// </summary>public IActionResult GetUserPage(string name, string type, int page, int size){PageResponse result = new PageResponse();UserBLL bll = new UserBLL();int total = 0;//总记录数int allPage = 0;//总分页数var list = bll.GetUserPage(name, type, page, size, ref total);if (list != null && list.Count > 0){allPage = GetAllPage(total, size);result.total = total;result.allPage = allPage;result.pageIndex = page;result.pageSize = size;result.data = list;}return Json(result);}/// <summary>/// 添加用户/// </summary>[HttpPost]public IActionResult AddUser(string name, string type){RestFulClass rfc = new RestFulClass();Userinfo user = new Userinfo(){Account = Guid.NewGuid().ToString(),Name = name,PWD = "123456",TYPE = type,IsDeleted = false,TAX = "",CreateBy = LOGIN_USER_NAME,CreateDate = DateTime.Now,};try{UserBLL bll = new UserBLL();var b = bll.AddUser(user);if (b)rfc.success = true;elserfc.success = false;}catch (Exception ex){rfc.success = false;rfc.message = ex.Message;}return Json(rfc);}/// <summary>/// 编辑用户/// </summary>[HttpPost]public IActionResult EditUser(string account, string name, string type){RestFulClass rfc = new RestFulClass();Userinfo user = new Userinfo(){Account = account,Name = name,TYPE = type,UpdateBy = LOGIN_USER_NAME,UpdateDate = DateTime.Now,};try{UserBLL bll = new UserBLL();var b = bll.EditUser(user);if (b)rfc.success = true;elserfc.success = false;}catch (Exception ex){rfc.success = false;rfc.message = ex.Message;}return Json(rfc);}/// <summary>/// 删除用户/// </summary>[HttpPost]public IActionResult DelUser(string account){RestFulClass rfc = new RestFulClass();try{if (!string.IsNullOrWhiteSpace(account)){UserBLL bll = new UserBLL();var b = bll.DelUser(account);if (b)rfc.success = true;elserfc.success = false;}else{rfc.success = false;rfc.message = "缺少需删除的用户id";}}catch (Exception ex){rfc.success = false;rfc.message = ex.Message;}return Json(rfc);}#endregion}
}

SqlSugar部分:

using SqlSugar;
using VoltageInvoiceDAL;
using VoltageInvoiceModel;namespace VoltageInvoiceBLL
{public class UserBLL{SqlSugarHelper sugar = new SqlSugarHelper();#region 登录验证/// <summary>/// 登录验证/// </summary>public Userinfo CheckLogin(string name, string pwd){var db = sugar.SqlClient();//数据库连接对象var user = db.Queryable<Userinfo>().Where(a => a.Name.Equals(name) && a.PWD.Equals(pwd) && a.IsDeleted == false).ToList().FirstOrDefault();//查询return user;//返回登录成功的用户对象}public Userinfo CheckUser(string account, string pwdOld){var db = sugar.SqlClient();//数据库连接对象var user = db.Queryable<Userinfo>().Where(a => a.Account.Equals(account) && a.PWD.Equals(pwdOld) && a.IsDeleted == false).ToList().FirstOrDefault();//查询return user;//返回登录成功的用户对象}/// <summary>/// 修改密码/// </summary>public bool ChangePwd(string account, string pwdNew){var db = sugar.SqlClient();//数据库连接对象string sql = $"update Userinfo set PWD='{pwdNew}' where Account='{account}'";int i = db.Ado.ExecuteCommand(sql);return i > 0;}#endregion#region 编辑用户/// <summary>/// 分页查询用户数据/// </summary>public List<Userinfo> GetUserPage(string name, string type, int pageNumber, int pageSize, ref int totalNumber){var db = sugar.SqlClient();//数据库连接对象var list = db.Queryable<Userinfo>().Where(a => a.IsDeleted == false).WhereIF(!string.IsNullOrWhiteSpace(name), (a => a.Name.Contains(name))).WhereIF(!string.IsNullOrWhiteSpace(type), (a => a.TYPE.Equals(type))).OrderBy(a => a.CreateDate, OrderByType.Desc).ToPageList(pageNumber, pageSize, ref totalNumber);int total = totalNumber;return list;}/// <summary>/// 新增用户/// </summary>public bool AddUser(Userinfo userinfo){var db = sugar.SqlClient();//数据库连接对象var i = db.Insertable(userinfo).ExecuteCommand();return i > 0;}/// <summary>/// 编辑用户/// </summary>public bool EditUser(Userinfo userinfo){var db = sugar.SqlClient();//数据库连接对象var i = db.Updateable(userinfo).IgnoreColumns(a => a.Account).IgnoreColumns(a => a.PWD).IgnoreColumns(a => a.IsDeleted).IgnoreColumns(a => a.TAX).IgnoreColumns(a => a.CreateBy).IgnoreColumns(a => a.CreateDate).Where(a => a.Account == userinfo.Account).ExecuteCommand();return i > 0;}/// <summary>/// 逻辑删除用户/// </summary>public bool DelUser(string account){var db = sugar.SqlClient();//数据库连接对象string sql = $"update Userinfo set IsDeleted=1 where Account='{account}'";// IsDeleted=1 逻辑删除int i = db.Ado.ExecuteCommand(sql);return i > 0;}#endregion}
}
using SqlSugar;
using VoltageInvoiceTools;namespace VoltageInvoiceDAL
{public class SqlSugarHelper{public string _connectionString = CustomConfigManager.GetConfig("ConnectionString:DB");//获取SQL连接字符串public SqlSugarClient _db = null;/// <summary>/// 构造函数(初始化)/// 调用方法:///  var db = sugar.SqlClient();/// var user = db.Queryable<Userinfo>().Where(a => a.Name.Equals(uid) && a.PWD.Equals(pwd)).ToList().FirstOrDefault();/// </summary>public SqlSugarClient SqlClient(){if (string.IsNullOrEmpty(_connectionString))throw new ArgumentNullException("数据库连接字符串为空");_db = new SqlSugarClient(new ConnectionConfig(){ConnectionString = _connectionString,//数据库连接字符串,见UI的appsettings.json内配置DbType = DbType.SqlServer,//数据库类型IsAutoCloseConnection = true,//自动断开连接MoreSettings = new ConnMoreSettings(){IsWithNoLockQuery = true,//为true表式查询的时候默认会加上.With(SqlWith.NoLock),IsAutoRemoveDataCache = true//为true自动清除缓存}});//输入最终SQL语句..._db.Aop.OnLogExecuting = (sql, pars) =>{var s1 = sql;//断点打在这里看内部生成的sql语句...};return _db;}}
}
{"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"AllowedHosts": "*",//数据库连接字符串:"ConnectionString": {"DB": "Server=.;Database=VoltageInvoiceDB;User ID=sa;Password=123456;"}}

界面预览:

本例源码下载: 

http://download.csdn.net/download/djk8888/88595401

这篇关于.NET Core6.0 MVC+layui+SqlSugar 简单增删改查的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/454097

相关文章

csu 1446 Problem J Modified LCS (扩展欧几里得算法的简单应用)

这是一道扩展欧几里得算法的简单应用题,这题是在湖南多校训练赛中队友ac的一道题,在比赛之后请教了队友,然后自己把它a掉 这也是自己独自做扩展欧几里得算法的题目 题意:把题意转变下就变成了:求d1*x - d2*y = f2 - f1的解,很明显用exgcd来解 下面介绍一下exgcd的一些知识点:求ax + by = c的解 一、首先求ax + by = gcd(a,b)的解 这个

hdu2289(简单二分)

虽说是简单二分,但是我还是wa死了  题意:已知圆台的体积,求高度 首先要知道圆台体积怎么求:设上下底的半径分别为r1,r2,高为h,V = PI*(r1*r1+r1*r2+r2*r2)*h/3 然后以h进行二分 代码如下: #include<iostream>#include<algorithm>#include<cstring>#include<stack>#includ

usaco 1.3 Prime Cryptarithm(简单哈希表暴搜剪枝)

思路: 1. 用一个 hash[ ] 数组存放输入的数字,令 hash[ tmp ]=1 。 2. 一个自定义函数 check( ) ,检查各位是否为输入的数字。 3. 暴搜。第一行数从 100到999,第二行数从 10到99。 4. 剪枝。 代码: /*ID: who jayLANG: C++TASK: crypt1*/#include<stdio.h>bool h

poj 1258 Agri-Net(最小生成树模板代码)

感觉用这题来当模板更适合。 题意就是给你邻接矩阵求最小生成树啦。~ prim代码:效率很高。172k...0ms。 #include<stdio.h>#include<algorithm>using namespace std;const int MaxN = 101;const int INF = 0x3f3f3f3f;int g[MaxN][MaxN];int n

uva 10387 Billiard(简单几何)

题意是一个球从矩形的中点出发,告诉你小球与矩形两条边的碰撞次数与小球回到原点的时间,求小球出发时的角度和小球的速度。 简单的几何问题,小球每与竖边碰撞一次,向右扩展一个相同的矩形;每与横边碰撞一次,向上扩展一个相同的矩形。 可以发现,扩展矩形的路径和在当前矩形中的每一段路径相同,当小球回到出发点时,一条直线的路径刚好经过最后一个扩展矩形的中心点。 最后扩展的路径和横边竖边恰好组成一个直

poj 1113 凸包+简单几何计算

题意: 给N个平面上的点,现在要在离点外L米处建城墙,使得城墙把所有点都包含进去且城墙的长度最短。 解析: 韬哥出的某次训练赛上A出的第一道计算几何,算是大水题吧。 用convexhull算法把凸包求出来,然后加加减减就A了。 计算见下图: 好久没玩画图了啊好开心。 代码: #include <iostream>#include <cstdio>#inclu

uva 10130 简单背包

题意: 背包和 代码: #include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <cmath>#include <stack>#include <vector>#include <queue>#include <map>

[MySQL表的增删改查-进阶]

🌈个人主页:努力学编程’ ⛅个人推荐: c语言从初阶到进阶 JavaEE详解 数据结构 ⚡学好数据结构,刷题刻不容缓:点击一起刷题 🌙心灵鸡汤:总有人要赢,为什么不能是我呢 💻💻💻数据库约束 🔭🔭🔭约束类型 not null: 指示某列不能存储 NULL 值unique: 保证某列的每行必须有唯一的值default: 规定没有给列赋值时的默认值.primary key:

如何在Visual Studio中调试.NET源码

今天偶然在看别人代码时,发现在他的代码里使用了Any判断List<T>是否为空。 我一般的做法是先判断是否为null,再判断Count。 看了一下Count的源码如下: 1 [__DynamicallyInvokable]2 public int Count3 {4 [__DynamicallyInvokable]5 get

2、PF-Net点云补全

2、PF-Net 点云补全 PF-Net论文链接:PF-Net PF-Net (Point Fractal Network for 3D Point Cloud Completion)是一种专门为三维点云补全设计的深度学习模型。点云补全实际上和图片补全是一个逻辑,都是采用GAN模型的思想来进行补全,在图片补全中,将部分像素点删除并且标记,然后卷积特征提取预测、判别器判别,来训练模型,生成的像