1.使用nuge添加引用(程序资源管理器)
2.program.cs
using FluentAssertions.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using NetModelCore02.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews(); //注册mvc服务
//取消大小写
builder.Services.AddMvc().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
//后台将值传递到前端首字母小写
builder.Services.AddDbContext<AJAXContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("SqlServerConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=UserInfo}/{action=IndexLU}/{id?}");
app.Run();
3.appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"SqlServerConnection": "Server=MPCOMPUTER;Database=Test;User Id=sa;Password=123456;Encrypt=True;TrustServerCertificate=True;"
},
"AllowedHosts": "*"
}
4.Index
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>.NET Core增删改查--layui</title>
<link href="~/layui-main/dist/css/layui.css" rel="stylesheet" />
</head>
<body>
@* 部分查询 表单 *@
<form class="layui-form" lay-filter="example" style="margin-top:20px">
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">姓名</label>
<div class="layui-input-inline">
<input type="text" name="Name" placeholder="请输入姓名" class="layui-input">
</div>
<div class="layui-inline">
<label class="layui-form-label">性别</label>
<div class="layui-input-block">
<input type="radio" name="Sex" value="全部" title="全部" checked="">
<input type="radio" name="Sex" value="男" title="男">
<input type="radio" name="Sex" value="女" title="女">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">部门</label>
<div class="layui-input-inline">
<select name="DeptId" lay-search="">
<option value="0">--请选择部门--</option>
@foreach (var d in (ViewData["DeptInfos"] as List<DeptInfo>))
{
<option value="@d.DeptId">@d.DeptName</option>
}
</select>
</div>
</div>
<div class="layui-inline">
<div class="layui-input-inline" style="width:400px">
<button type="button" lay-submit="" lay-filter="demo1" class="layui-btn layui-btn-normal">查询</button>
<button type="button" class="layui-btn layui-btn-danger" onclick="Add()">添加</button>
</div>
</div>
</div>
</div>
</form>
@* 添加表单 *@
<form class="layui-form" action="" lay-filter="AddUser" id="MyModel" hidden="hidden">
<input type="hidden" name="Id" placeholder="请输入编号" class="layui-input">
<div class="layui-form-item">
<label class="layui-form-label">姓名</label>
<div class="layui-input-block">
<input type="text" name="Name" placeholder="请输入姓名" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">性别</label>
<div class="layui-input-block">
<input type="radio" name="Sex" value="男" title="男" checked="">
<input type="radio" name="Sex" value="女" title="女">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">年龄</label>
<div class="layui-input-block">
<input type="text" name="Age" placeholder="请输入年龄" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">电话</label>
<div class="layui-input-block">
<input type="text" name="Tel" placeholder="请输入电话" class="layui-input">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">部门</label>
<div class="layui-input-inline">
<select name="DeptId" lay-search="" id="DeptId">
<option value="0">--请选择部门--</option>
@foreach (var d in (ViewData["DeptInfos"] as List<DeptInfo>))
{
<option value="@d.DeptId">@d.DeptName</option>
}
</select>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
@* <button type="button" class="layui-btn layui-btn-normal" id="LAY-component-form-setval">赋值</button>
<button type="button" class="layui-btn layui-btn-normal" id="LAY-component-form-getval">取值</button> *@
<button type="button" class="layui-btn" lay-submit="" lay-filter="demo2" style="margin-top:10px">保存</button>
</div>
</div>
</form>
@* 表格 *@
<table class="layui-hide" id="test"></table>
@* 操作按钮 *@
<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 src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/layui-main/dist/layui.js"></script>
<script>
var layer;
layui.use(['table','layer','form'], function () {
var table = layui.table; //layui和.NET Core一样,用啥就要引用啥
layer = layui.layer;
var form = layui.form;//提交表单
table.render({
elem: '#test',
url: '/UserInfo/IndexLDG',
// cellMinWidth: 80, //全局定义常规单元格的最小宽度,layui 2.2.1 新增
cols: [[
{ type: 'checkbox' },
{ field: 'Id', width: 200, title: '编号', sort: true, align: 'center' },
{ field: 'Name', width: 200, title: '用户名',align:'center' },
{
field: 'Sex', width: 200, title: '性别', sort: true, align: 'center',
templet: function (d) {
if(d.Sex == "男")
return '<span style="color:blue;">男</span>'
else
return '<span style="color:red;">女</span>'
}
},
{ field: 'Age', width: 200, title: '年龄', sort: true, align: 'center' },
{ field: 'Tel', width: 100, title: '电话', sort: true, align: 'center' },
{ field: 'DeptName', width: 400, title: '部门', sort: true, align: 'center' },
// {
// field: 'id', width: 200, title: '操作', align: 'center',align:'center',
// templet: function (row) {
// return `
// <button onclick="Delete(${row.id})" type="button" class="layui-btn layui-bg-orange">删除</button>
// <button onclick="Edit(${row.id})" type="button" class="layui-btn layui-bg-blue">修改</button>
// `;
// }
// }
{ fixed: 'right', field:'-', title: '操作', toolbar: '#barDemo', width: 150 }
// { field: 'sign', title: '签名', width: '30%', minWidth: 100 }, //minWidth:局部定义当前单元格的最小宽度,layui 2.2.1 新增
]],
page: true
});
//监听提交(部分查询)
form.on('submit(demo1)', function(data){
// layer.alert(JSON.stringify(data.field), {
// title: '最终的提交信息'
// })
table.reload('test', {
where: { //设定异步数据接口的额外参数,任意设
Name: data.field.Name,
Sex: data.field.Sex,
DeptId: data.field.DeptId
}
, page: {
curr: 1 //重新从第 1 页开始
}
}); //只重载数据
return false; //阻止刷新
});
//监听提交(保存)
form.on('submit(demo2)', function (data) {
// layer.alert(JSON.stringify(data.field), {
// title: '最终的提交信息'
// })
//使用ajax
$.ajax({
type:"post",
url: "/UserInfo/AddUser",
dataType:"json",
data:data.field,
success: function (data) {
if (data) {
layer.msg('保存成功!', { icon: 1, time: 0 });
setTimeout(function () {
// 关闭弹出层(如果有弹出层的话 关闭所有的)
parent.layer.closeAll();
// // 刷新表格
// dataTable();
window.location.href = "/UserInfo/IndexLU";
}, 2000); // 3000 毫秒(3 秒)后关闭弹窗并刷新表格
}else{
layer.msg('保存失败!', { icon: 2, time: 2000 });
}
}
})
return false; //阻止刷新
});
//监听行工具事件
table.on('tool(test)', function (obj) {
var data = obj.data; //当前点击的一行值 类似bootstrap中的formatter中的row参数,获取当前行的值
if (obj.event === 'del') {
layer.confirm('你确定要删除吗?', function (index) {
// obj.del();
// layer.close(index);
$.getJSON("/UserInfo/DeleteUser", { Id: data.Id }, function (data) {
layer.msg('删除成功!', { icon: 1, time: 0 });
setTimeout(function () {
// 关闭弹出层(如果有弹出层的话 关闭所有的)
parent.layer.closeAll();
// 刷新表格
window.location.href = "/UserInfo/IndexLU";
}, 3000); // 3000 毫秒(3 秒)后关闭弹窗并刷新表格
})
});
} else if (obj.event === 'edit') {
// 在此处输入 layer 的任意代码
layer.open({
type: 1, // page 层类型
area: ['600px', '400px'],
title: '修改页面',
shade: 0.6, // 遮罩透明度
shadeClose: true, // 点击遮罩区域,关闭弹层
maxmin: true, // 允许全屏最小化
anim: 0, // 0-6 的动画形式,-1 不开启
content: $("#MyModel")
});
$.getJSON("/UserInfo/GetUsersByID", { Id: data.Id }, function (data) {
form.val('AddUser', data);
form.render(); //复选框、单选按钮、下拉框可用 重新加载
})
}
});
});
//添加
function Add(){
// 在此处输入 layer 的任意代码
layer.open({
type: 1, // page 层类型
area: ['600px', '400px'],
title: '添加页面',
shade: 0.6, // 遮罩透明度
shadeClose: true, // 点击遮罩区域,关闭弹层
maxmin: true, // 允许全屏最小化
anim: 0, // 0-6 的动画形式,-1 不开启
content: $("#MyModel")
});
}
</script>
</body>
</html>
5.控制器
1.查询表格
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NetModelCore02.Models;
using System.Linq;
namespace NetModelCore02.Controllers
{
public class UserInfoController : Controller
{
private readonly AJAXContext db;
public UserInfoController(AJAXContext _db)
{
//通过构造方法依赖注入
db = _db;
}
public IActionResult Index()
{
return View();
}
/// <summary>
///主视图
/// </summary>
/// <returns></returns>
public IActionResult IndexLU()
{
//绑定下拉框
ViewData["DeptInfos"] = db.DeptInfos.ToList();
return View();
}
/// <summary>
/// 查询 Layui 部分查询
/// </summary>
/// <param name="pageNumber">页数</param>
/// <param name="pageSize">页码</param>
/// <returns></returns>
public async Task<IActionResult> IndexLDG(int page = 1, int limit = 10,string Name="",string Sex="全部",int DeptId = 0)
{
//Name为空的时候
if (Name == null) Name = "";
//异步
var list = await (from u in db.UserInfos
join d in db.DeptInfos
on u.DeptId equals d.DeptId
where ((Name=="")||(u.Name.Contains(Name))) && ((Sex=="全部")||(u.Sex == Sex)) && ((DeptId == 0)||(u.DeptId == DeptId))
select new
{
u.Id,
u.Name,
u.Sex,
u.Age,
u.Tel,
d.DeptName,
}).ToListAsync();
var json = new
{
code = "0",
msg = "",
count = list.Count,
data = list.OrderBy(u => u.Id).Skip((page - 1) * limit).Take(limit)
};
return Json(json);
}
}
}
2.添加 修改在同一个页面
/// <summary>
/// 添加 修改
/// </summary>
/// <param name="u"></param>
/// <returns></returns>
public async Task<IActionResult> AddUser(Models.UserInfo u)
{
int i = 0;
//添加
if (u.Id == 0)
{
db.UserInfos.Add(u);
i = await db.SaveChangesAsync();
}
//修改 Sex='" + u.Sex + "' and Tel='" + u.Tel + "' and Age='" + u.Age + "' and DeptId='" + u.DeptId +"'
else
{
//string sql = "update UserInfo set Name='" + u.Name + "' where Id=" + u.Id;
string sql = "update UserInfo set Name='" + u.Name + "', Sex='" + u.Sex + "' , Tel='" + u.Tel + "' ,Age='" + u.Age + "', DeptId='" + u.DeptId +"' where Id=" + u.Id;
i = await db.Database.ExecuteSqlRawAsync(sql);
}
return Json(i > 0);
}
/// <summary>
/// 找到要删除的Id
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public async Task<IActionResult> GetUsersByID(int Id)
{
Models.UserInfo u = await db.UserInfos.FindAsync(Id);
return Json(u);
}
3.删除
/// <summary>
/// 删除操作
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public async Task<IActionResult> DeleteUser(int Id)
{
var user = await db.UserInfos.FindAsync(Id);
if (user != null)
{
db.UserInfos.Remove(user);
await db.SaveChangesAsync();
return Json(true);
}
else
{
return Json(false);
}
}
6.在程序包管理器控制台执行语句(生成models模型类)
(忘记上面写这个了!!!!!!!!)
//sqlserver
Scaffold-DbContext "Server=.;User Id=sa;Password=123;Database=MaterialsManagementInfo;Persist Security Info=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models -f
//MySQL
Scaffold-DbContext "server=localhost;userid=root;pwd=03047237;port=3306;database=userinfo;sslmode=none;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -Force
//Oracle
Scaffold-DbContext "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)));User Id=zzz;Password=123456;" Oracle.EntityFrameworkCore -O Models -F
标签:Core,layer,Name,db,EF,改查,field,data,Id
From: https://blog.csdn.net/MxxJxF/article/details/143103484