1.实现简单的增删改查(Asp.Net MVC+Layui)
实现简单的增删改查(Asp.Net MVC+Layui)
实现简单的增删改查(Asp.Net MVC+Layui)
一、页面效果
1、分页
2、新增
3、删除
4、修改
5、查询
二、代码链接
https://download.csdn.net/download/zeron01/89712188
三、前期准备
1、新建项目
打开visual studio 2019,选择项目模板
点击“下一步”
2、 在项目中新建文件夹(设置mvc的雏形)
创建3个文件夹(BLL、Commons、DAL)
3、连接数据库(SqlServer)
1)在Commons文件夹下添加.cs文件
2)读取参数
JdbcUtil.cs代码:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
/// <summary>
/// 连接数据库---工具类
/// </summary>
namespace WebApplication5.Commons
{
public class JdbcUtil
{
//与数据库连接,从Web.config中读取参数
public static string MyConn = ConfigurationManager.AppSettings["connectionstring"];
public static SqlConnection conn = new SqlConnection(MyConn);
/// <summary>
/// 查询数据,查询结束后手动关闭数据库连接
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public SqlDataReader select(string sql)
{
SqlDataReader reader = null;
conn.Open();
SqlCommand comm = new SqlCommand(sql, conn);
reader = comm.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
return reader;
}
//删除、添加、更改
public static int ExecuteUpdate(string sql)
{
int result = 0;
conn.Open();
SqlCommand comm = new SqlCommand(sql, conn);
result = comm.ExecuteNonQuery();
conn.Close();
return result;
}
//单条数据的查询
public static Object ExecteOnlyOneVaule(string sql)
{
Object obj = null;
conn.Open();
SqlCommand comm = new SqlCommand(sql, conn);
obj = comm.ExecuteScalar();
conn.Close();
return obj;
}
}
}
3)在数据库中新建表
use Demo;
create table Student (
Sid int primary key IDENTITY(1,1) ,
Name varchar(50) not null,
Sex varchar(2) not null,
Birthday datetime,
ClassName varchar(30) ,
ProfessionalName varchar(30),
);
4)在VS2019中建立对应的实体类
4、简单的实现查询所有数据功能
1) DAL层(DAL文件夹中)新建项“StudentDAL.cs”
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using WebApplication5.Commons;
using WebApplication5.Models;
namespace WebApplication5.DAL
{
public class StudentDAL
{
/// <summary>
/// 查询所有的数据--根据搜索参数
/// </summary>
/// <returns></returns>
public List<Student> GetAll(string key)
{
List<Student> studentList = new List<Student>();
JdbcUtil jdbcUtil = new JdbcUtil();
string query = "select * from Student where 1=1 ";
if (!string.IsNullOrEmpty(key))//有参数输入参数,进行搜索的功能
{
query += string.Format(" and ( Name like '%{0}%' or ClassName like '%{0}%' or ProfessionalName like '%{0}%' ) ", key);
}
SqlDataReader data=jdbcUtil.select(query);
while (data.Read())//将数据读取到,存到list集合中
{
Student student = new Student();
student.Sid = (int)data["Sid"];
student.Name = (string)data["Name"];
student.Sex = (string)data["Sex"];
student.Birthday = (DateTime)data["Birthday"];
student.ClassName = (string)data["ClassName"];
student.ProfessionalName = (string)data["ProfessionalName"];
studentList.Add(student);
}
JdbcUtil.conn.Close();//关闭数据库的连接
return studentList;
}
}
}
2) BLL层新建项“StudentBLL.cs”
3) Controller层新建 " StudentController",
1)选择 添加“控制器
2)在StudentController中生成相应的视图
i)代码
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication5.BLL;
using WebApplication5.Commons;
using WebApplication5.Models;
namespace WebApplication5.Controllers
{
public class StudentController : Controller
{
private StudentBLL studentBLL = new StudentBLL();
// GET: Student
public ActionResult Index()
{
return View();
}
/// <summary>
/// 没有加layui表格的数据展示
/// </summary>
/// <returns></returns>
public ActionResult GetAll()
{
string key = "";
List<Student> students= studentBLL.GetAll(key);
return View(students);
}
}
}
ii)操作
在Views下自动生成文件夹Student及“GetAll.cshtml”,代码自动生成
@model IEnumerable<WebApplication5.Models.Student>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Sid)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Sex)
</th>
<th>
@Html.DisplayNameFor(model => model.Birthday)
</th>
<th>
@Html.DisplayNameFor(model => model.ClassName)
</th>
<th>
@Html.DisplayNameFor(model => model.ProfessionalName)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Sid)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sex)
</td>
<td>
@Html.DisplayFor(modelItem => item.Birthday)
</td>
<td>
@Html.DisplayFor(modelItem => item.ClassName)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProfessionalName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
3)效果图
5、使用Layui改变页面样式
1、 下载layui并导入项目
压缩包解压,然后将文件夹复制到项目里
2、修改Views/Shared/_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>后台管理系统 - My ASP.NET Application</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="~/layui/css/layui.css">
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/modernizr-2.8.3.js"></script>
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
<div class="layui-header">
<div class="layui-main">
<div class="layui-logo">后台管理系统</div>
<ul class="layui-nav" style="position: fixed; top: 0; right: 0; background: none;" lay-filter="nav-top">
<li class="layui-nav-item">
<dl class="layui-nav-child">
<dd><a href="javascript:;">退出</a></dd>
</dl>
</li>
</ul>
</div>
</div>
<div class="layui-side layui-bg-black">
<div class="layui-side-scroll">
<ul class="layui-nav layui-nav-tree" lay-filter="navSlide">
@Html.Raw(ViewBag.MenuItems)
</ul>
</div>
</div>
<div class="layui-body">
<div class="layui-fluid">
@RenderBody()
@RenderSection("content", false)
</div>
</div>
</div>
</body>
</html>
3、新建controller(BaseController),----初始化_Layout.cshtml中的值,完成侧边栏
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
//进行初始化,其他的Controller是基于此进行
namespace WebApplication5.Controllers
{
public class BaseController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
SetMenu();
}
private void SetMenu()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("<li class=\"layui-nav-item {0}\">", "aaaa");
sb.AppendFormat("<a class='layui-icon {0}' href=\"{1}\">  {2}</a>", "layui-icon-menu-fill", "/Student/Index", "首页");//设置好路由,方便跳转页面
sb.AppendFormat("</li>");
sb.AppendFormat("<li class=\"layui-nav-item {0}\">", " ");
sb.AppendFormat("<a class='layui-icon {0}' href=\"{1}\">  {2}</a>", "layui-icon-set", "/Student/GetAll", "学生管理");
sb.AppendFormat("</li>");
sb.AppendFormat("<li class=\"layui-nav-item {0}\">", " ");
sb.AppendFormat("<a class='layui-icon {0}' href=\"{1}\">  {2}</a>", "layui-icon-user", "/Student/ShowDate", "学生管理w");
sb.AppendFormat("</li>");
ViewBag.MenuItems = sb.ToString();
}
}
}
4、其他controller 继承BaseController。
5、在StudentController中新建一个方法返回一个页面,使用Layui改变表格整体样式,可以先复制官网范例,然后修改css路径、JS 路径。
6、在StudentController中创建一个方法返回Json数据,在5、的页面中使用该url。
7、数据显示时,生日日期 显示有误,需要改变其格式。
(思路)新建一个类JsonNetResult 继承JsonResult,重写ExecuteResult()方法,从而改变日期格式。
四、代码
1、Commons层
JsonNetResult
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
/// <summary>
/// 在使用json 改变数据格式时,对 日期进行修改(重写 ExecuteResult方法)
/// </summary>
namespace WebApplication5.Commons
{
public class JsonNetResult : JsonResult
{
public object Data { get; set; }
public string DateTimeFormat { get; set; }
public JsonNetResult()
{
}
public JsonNetResult(object dat,JsonRequestBehavior jsonRequest)
{
this.Data = dat;
base.JsonRequestBehavior = jsonRequest;
this.DateTimeFormat = "yyyy年MM月dd日";
}
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data != null)
{
/* JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting.Indented };
JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings());
serializer.Serialize(writer, Data);
writer.Flush();*/
IsoDateTimeConverter isoDateTimeConverter = new IsoDateTimeConverter();
//设置日期格式
isoDateTimeConverter.DateTimeFormat = DateTimeFormat;
//序列化
string jsonResult = JsonConvert.SerializeObject(this.Data, isoDateTimeConverter);
response.Write(jsonResult);
}
}
}
}
2、DAL层
StudentDAL
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using WebApplication5.Commons;
using WebApplication5.Models;
namespace WebApplication5.DAL
{
public class StudentDAL
{
/// <summary>
/// 查询所有的数据--根据搜索参数
/// </summary>
/// <returns></returns>
public List<Student> GetAll(string key)
{
List<Student> studentList = new List<Student>();
JdbcUtil jdbcUtil = new JdbcUtil();
string query = "select * from Student where 1=1 ";
if (!string.IsNullOrEmpty(key))//有参数输入参数,进行搜索的功能
{
query += string.Format(" and ( Name like '%{0}%' or ClassName like '%{0}%' or ProfessionalName like '%{0}%' ) ", key);
}
SqlDataReader data=jdbcUtil.select(query);
while (data.Read())//将数据读取到,存到list集合中
{
Student student = new Student();
student.Sid = (int)data["Sid"];
student.Name = (string)data["Name"];
student.Sex = (string)data["Sex"];
student.Birthday = (DateTime)data["Birthday"];
student.ClassName = (string)data["ClassName"];
student.ProfessionalName = (string)data["ProfessionalName"];
studentList.Add(student);
}
JdbcUtil.conn.Close();//关闭数据库的连接
return studentList;
}
/// <summary>
/// 分页--数据
/// </summary>
/// <param name="key"></param>
/// <param name="page"></param>
/// <returns></returns>
public List<Student> GetDateByPage(string key,Page page)
{
List<Student> studentList = new List<Student>();
JdbcUtil jdbcUtil = new JdbcUtil();
string query = string.Format("select * from(select *, ROW_NUMBER() OVER(order by Sid) as RowId from Student) as b where RowId between {0} and {1} ", page.PageSize * (page.PageNum - 1) + 1, page.PageSize * page.PageNum);//RowId between {0} and {1} 。 范围[start,end],start从1开始。如 between 2 and 4==>2、3、4
if (!string.IsNullOrEmpty(key))//有参数输入参数,进行搜索的功能
{
query = string.Format("select * from(select*, ROW_NUMBER() OVER(order by Sid) as RowId from Student where ( Name like '%{0}%' or ClassName like '%{0}%' or ProfessionalName like '%{0}%') ) as b where RowId between {1} and {2} ", key, page.PageSize * (page.PageNum - 1) + 1, page.PageSize * page.PageNum);
}
SqlDataReader data = jdbcUtil.select(query);
while (data.Read())//将数据读取到,存到list集合中
{
Student student = new Student();
student.Sid = (int)data["Sid"];
student.Name = (string)data["Name"];
student.Sex = (string)data["Sex"];
student.Birthday = (DateTime)data["Birthday"];
student.ClassName = (string)data["ClassName"];
student.ProfessionalName = (string)data["ProfessionalName"];
studentList.Add(student);
}
JdbcUtil.conn.Close();//关闭数据库的连接
return studentList;
}
/// <summary>
/// 根据id判断,学生信息是否已存在
/// </summary>
/// <param name="ss"></param>
/// <returns></returns>
public bool SelBySid(int ss)
{
string query = string.Format( "select * from Student where Sid='{0}' ",ss);
var IsExitSid = JdbcUtil.ExecteOnlyOneVaule(query);//调用方法,查看该数据是否存在
if (IsExitSid != null)
{
return true;//已存在 该 id
}
else { return false; }
}
/// <summary>
/// 新增数据
/// </summary>
/// <param name="student"></param>
/// <returns></returns>
public bool AddStudent(Student student)
{
string insertSql = string.Format("insert into Student values('{0}','{1}','{2}','{3}','{4}','{5}')", student.Sid, student.Name, student.Sex, student.Birthday, student.ClassName, student.ProfessionalName);
int res=JdbcUtil.ExecuteUpdate(insertSql);
if (res == 1)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 编辑学生
/// </summary>
/// <param name="student"></param>
/// <returns></returns>
public bool EditStudent(Student student)
{
string updSql = string.Format("update Student set Name='{0}',Sex='{1}',Birthday='{2}',ClassName='{3}',ProfessionalName='{4}' where Sid='{5}' ", student.Name, student.Sex,student.Birthday,student.ClassName, student.ProfessionalName,student.Sid);
int res = JdbcUtil.ExecuteUpdate(updSql);
if (res == 1)
{
return true;
}
else { return false; }
}
/// <summary>
/// 根据学生id 来删除数据
/// </summary>
/// <param name="sid"></param>
/// <returns></returns>
public bool DeleteStudent(int sid)
{
string delSql = string.Format("delete from Student where Sid='{0}' ", sid);
int res= JdbcUtil.ExecuteUpdate(delSql);
if (res == 1)
{
return true;
}
else { return false; }
}
}
}
3、BLL层
StudentBLL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebApplication5.DAL;
using WebApplication5.Models;
namespace WebApplication5.BLL
{
public class StudentBLL
{
private StudentDAL studentDAL = new StudentDAL();
public List<Student> GetAll(string key)
{
return studentDAL.GetAll(key);
}
public List<Student> GetDateByPage(string key, Page page)
{
return studentDAL.GetDateByPage(key, page);
}
public bool SelBySid(int ss)
{
return studentDAL.SelBySid(ss);
}
public bool AddStudent(Student student)
{
return studentDAL.AddStudent(student);
}
public bool EditStudent(Student student)
{
return studentDAL.EditStudent(student);
}
public bool DeleteStudent(int sid)
{
return studentDAL.DeleteStudent(sid);
}
}
}
4、Controllers层
StudentController
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication5.BLL;
using WebApplication5.Commons;
using WebApplication5.Models;
namespace WebApplication5.Controllers
{
public class StudentController : BaseController
{
private StudentBLL studentBLL = new StudentBLL();
// GET: Student
public ActionResult Index()
{
return View();
}
/// <summary>
/// 没有加layui表格的数据展示
/// </summary>
/// <returns></returns>
public ActionResult GetAll()
{
string key = "";
List<Student> students= studentBLL.GetAll(key);
return View(students);
}
/// <summary>
/// 使用这个,返回一个页面。(增删改查 在此页面上进行)
/// </summary>
/// <returns></returns>
public ActionResult ShowDate()
{
return View();
}
/// <summary>
/// 使用layui 显示数据--只作为一个方法,不能将它作为一个视图!!(没有改日期的格式,调用的是JsonResult返回值)
/// http://localhost:56959/Student/ShowDate
/// </summary>
/// <returns></returns>
[HttpPost]
public JsonResult UseLayGetDate(string key)
{
List<Student> students = studentBLL.GetAll(key);
return Json(new { code = 0, data = students, msg = "" });
}
/// <summary>
/// 出生日期的格式已修改。新建一个类JsonNetResult 继承JsonResult,重写ExecuteResult()方法。
/// </summary>
/// <returns></returns>
[HttpPost]
public JsonResult UseLayGetDate2(string key)
{
List<Student> students = studentBLL.GetAll(key);
//出生日期的格式要修改:
return new JsonNetResult(new { code = 0, data = students},JsonRequestBehavior.AllowGet);
}
/// <summary>
/// 添加了分页
/// </summary>
/// <param name="key"></param>
/// <param name="layout"></param>
/// <param name="page"></param>
/// <param name="limit"></param>
/// <returns></returns>
public JsonResult UseLayGetDate3(string key,string[] layout, int page ,int limit)
{//进行分页,使用那两个参数
string[] ss = layout;
Page page1 = new Page();
page1.PageNum = page;
page1.PageSize = limit;
List<Student> students = studentBLL.GetDateByPage(key, page1);
int Count = studentBLL.GetAll(key).Count;//根据key获得的学生总数
//出生日期的格式要修改:
return new JsonNetResult(new { code = 0, count = Count, data = students, msg = "" }, JsonRequestBehavior.AllowGet);
}
/// <summary>
/// 新增学生:先进行判断学号是否已存在
/// 重点:JsonConvert.DeserializeObject 将string的obj==>指定类数据
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public JsonResult Add(string param)
{
int Hcode;
string Hmsg;
var ss = param;
Student student = JsonConvert.DeserializeObject<Student>(param);
if (studentBLL.SelBySid(student.Sid))
{
Hcode = 1;
Hmsg = "该学号已存在,请重新输入!";
}
else
{
bool IsAdd = studentBLL.AddStudent(student);
if (!IsAdd)
{
Hcode = 1;
Hmsg = "新增失败";
}
else
{
Hcode = 0;
Hmsg = "新增成功";
}
}
return Json(new { code = Hcode,msg=Hmsg });
}
/// <summary>
/// 修改学生信息
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public JsonResult Edit(string param)
{
int Hcode;
string Hmsg;
Student student = JsonConvert.DeserializeObject<Student>(param);
bool IsEdit = studentBLL.EditStudent(student);
if (!IsEdit)
{
Hcode = 1;
Hmsg = "修改失败";
}
else
{
Hcode = 0;
Hmsg = "修改成功";
}
return Json(new { code = Hcode, msg = Hmsg });
}
public JsonResult Delete(int sid)
{
int Hcode;
string Hmsg;
bool IsEdit = studentBLL.DeleteStudent(sid);
if (!IsEdit)
{
Hcode = 1;
Hmsg = "删除失败";
}
else
{
Hcode = 0;
Hmsg = "删除成功";
}
return Json(new { code = Hcode, msg = Hmsg });
}
}
}
5、Models层
(1)Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//分页 参数
namespace WebApplication5.Models
{
public class Page
{
public int PageNum { get; set; }//页数
public int PageSize { get; set; }//每页大小
}
}
(2)Student
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication5.Models
{
public class Student
{
public int Sid { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public DateTime Birthday { get; set; }
public string ClassName { get; set; }
public string ProfessionalName { get; set; }
}
}
6、Views/Student
(1)Index.cshtml
<h2>Hello</h2
(2)ShowDate.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Layui</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/css/layui.css" media="all">
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body>
<div class="layui-row">
<div class="layui-col-xs6">
<div class="grid-demo grid-demo-bg1">
<div class="SearDiv">
搜索参数(姓名、班级名称或者专业名称):
<div class="layui-inline">
<input class="layui-input" name="id" id="SearParameter" autocomplete="off">
</div>
<button class="layui-btn " data-type="reload" type="button">
<i class="layui-icon layui-icon-search">搜索</i>
</button>
</div>
</div>
</div>
<div class="layui-col-xs6">
<div class="grid-demo">
<button class="layui-btn layui-btn-warm" type="button" id="AddBtn">
<i class="layui-icon layui-icon-addition">新增</i>
</button>
</div>
</div>
</div>
<table id="test" lay-filter="laf_tab"></table> @*显示数据*@
<script type="text/html" id="switchTpl">
<input type="checkbox" name="sex" value="{{d.Sex}}" lay-skin="switch" lay-text="女|男" lay-filter="sexDemo" {{ d.Sex == '女' ? 'checked' : '' }}>
</script>
@*新增的弹出层内容,先隐藏*@
<div class="site-text" style="margin: 5%; display: none" id="AddFormDiv" >
<form class="layui-form" id="AddForm" method="post" lay-filter="example">
<div class="layui-form-item">
<div class="layui-inline" id="sid_div">
<label class="layui-form-label">学号</label>
<div class="layui-input-block">
<input type="text" name="Sid" id="Sid" lay-verify="sid" autocomplete="off" placeholder="请输入学号" class="layui-input">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">姓名</label>
<div class="layui-input-block">
<input type="text" name="Name" id="Name" autocomplete="off" placeholder="请输入姓名" lay-verify="required" class="layui-input">
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<div class="layui-form-item">
<label class="layui-form-label">性别</label>
<div class="layui-input-block" id="Che">
<input type="radio" name="Sex" value="男" title="男" checked="">
<input type="radio" name="Sex" value="女" title="女">
</div>
</div>
</div>
<div class="layui-inline">
<div class="layui-inline">
<label class="layui-form-label">出生日期</label>
<div class="layui-input-block">
<input type="text" name="date" id="Birthday" autocomplete="off" lay-verify="required" placeholder="yyyy年MM月dd日" class="layui-input">
</div>
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">班级</label>
<div class="layui-input-block">
<input type="text" name="ClassName" id="ClassName" lay-verify="ClassName" autocomplete="off" placeholder="请输入班级" class="layui-input">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">专业</label>
<div class="layui-input-block">
<input type="text" name="ProfessionalName" id="ProfessionalName" autocomplete="off" lay-verify="required" placeholder="请输入专业" class="layui-input">
</div>
</div>
</div>
</form>
</div>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-normal layui-icon layui-icon-edit" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-icon layui-icon-delete" lay-event="del">删除</a>
</script>
<script src="~/layui/layui.js" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述 JS 路径需要改成你本地的 -->
<script>
layui.use('table', function () {
var table = layui.table
, form = layui.form;
//给表格中的数据进行赋值
table.render({
elem: '#test'
// , where: { key: ''} //扩展参数,可以传数据到后台
, method: 'post' //提交方式
, url: '/Student/UseLayGetDate3' //修改url路径
, cellMinWidth: 80//初始化最小列宽
, cols: [[//显示列名及数据(field值为后台所传递的json数据data里)
{ type: 'numbers' }
// , { type: 'checkbox' }
, { field: 'Sid', title: 'ID', width: 100, unresize: true, sort: true }
, { field: 'Name', title: '用户名', align: 'center', templet: '#usernameTpl' }
, { field: 'Sex', title: '性别', width: 85, templet: '#switchTpl', unresize: true }
, { field: 'Birthday', title: '出生日期', align: 'center', sort: true }
, { field: 'ClassName', title: '班级', minWidth: 120, }
, { field: 'ProfessionalName', title: '专业', align: 'center' }
, { fixed: 'right', width: 250, align: 'center', toolbar: '#barDemo', title: '操作' }
]]
, page: true//开启分页,此时相当于给后端传递了2个参数(page当前页数、limit每页最大数据量)
});
//监听性别操作
form.on('switch(sexDemo)', function (obj) {
layer.tips(this.value + ' ' + this.name + ':' + obj.elem.checked, obj.othis);
});
//查询---输入的参数
var $ = layui.$;
var active = {
reload: function () {
var SearParameter = $('#SearParameter');
//执行重载
table.reload('test', {//test 当前容器的实例 ==> table.render({.....
page: {
curr: 1 //重新从第 1 页开始--分页
},
where: {
key: SearParameter.val()
}
});
}
};
$('.SearDiv .layui-btn').on('click', function () {
var type = $(this).data('type');
active[type] ? active[type].call(this) : '';
});
var t1_sid = document.getElementById('sid_div');//选取id为test的div元素
//监听单元格事件----编辑、删除按钮
table.on('tool(laf_tab)', function (obj) {
var data = obj.data;
console.log(obj);
if (obj.event === 'edit') {
// console.log("编辑");
t1_sid.style.display = 'none';// 隐藏选择的元素---将sid隐藏
var editLay = layer.open({
type: 1 //Page层类型
, skin: 'layui-layer-molv'
, area: ['700px', '430px']
, title: ['修改学生信息', 'font-size:18px']
, btn: ['保存', '取消']
, shadeClose: true
, shade: 0 //遮罩透明度
// , maxmin: true //允许全屏最小化
, content: $("#AddFormDiv") //一个content的内容,两个layer弹层一起用,区别在于 sid是否可见
@* , success: function () {
$("#Sid").val(data.Sid);
$("#Name").val(data.Name);
$("#ClassName").val(data.ClassName);
$("#ProfessionalName").val(data.ProfessionalName);
$("#Birthday").val(data.Birthday);
// $("#AddForm")[0].reset();
}*@
, success: function (layero, index) {
$("#Sid").val(data.Sid);
$("#Name").val(data.Name);
$("#ClassName").val(data.ClassName);
$("#ProfessionalName").val(data.ProfessionalName);
$("#Birthday").val(data.Birthday);
//弹出层---进行校验1、将弹出层的确定按钮 转为layui的form提交按钮 2、写自定义的校验规则 3、通过from.on实现
//1.1 条件form标识
layero.addClass('layui-form');
//1.2 将保存按钮转为提交按钮
layero.find('.layui-layer-btn0').attr({
'lay-filter': 'formButton',
'lay-submit': ''
})
}
, yes: function () {//yes表示定义的第一个按钮
//3.1 点击form表单的 "提交"按钮,会先进行自定义的校验
form.on('submit(formButton)', function () {
var stu = {};
var Sid = $("#Sid").val();
var Name = $("#Name").val();
var ClassName = $("#ClassName").val();
var ProfessionalName = $("#ProfessionalName").val();
var Birthday = $("#Birthday").val();
var Sex = $("#Che input[name='Sex']:checked").val();
stu.Sid = Sid;
stu.Name = Name;
stu.ClassName = ClassName;
stu.ProfessionalName = ProfessionalName;
stu.Birthday = Birthday;
stu.Sex = Sex;
//console.log(stu);
// alert(JSON.stringify(stu));
$.ajax({
url: '/Student/Edit',
data: {
param: JSON.stringify(stu)
},
type: 'Post',
success: function (res) {
if (res.code === 0) {
layer.close(editLay);//关闭当前窗口
layer.alert(res.msg);
//当前数据进行刷新,新增内容清空
table.reload('test');
}
else {
layer.alert(res.msg);
}
}
})
})
}
});
} else if (obj.event === 'del') {
var mm2 = '真的删除该条(学号:' + data.Sid + ')数据吗?';
layer.confirm(mm2, function (index) {
$.ajax({
url: '/Student/Delete',
data: {
sid: data.Sid
},
type: 'Post',
success: function (res) {
if (res.code === 0) {
layer.close(index);
table.reload('test');
}
else {
layer.close(index);
layer.msg(res.msg, { icon: 5});
// layer.alert(res.msg);
}
}
});
});
}
});
//日期显示
var laydate = layui.laydate;
//自定义日期格式的用法
laydate.render({
elem: '#Birthday'
,format: 'yyyy年MM月dd日'
});
//自定义验证规则
form.verify({
ClassName: function (value) {
if (value.length < 5) {
return '班级至少得5个字符啊';
}
}
, sid: [
/^[\S]{1,4}$/
, '学号必须1到4位,且不能出现空格'
]
, content: function (value) {
layedit.sync(editIndex);
}
});
var $ = layui.$;
//新增 按钮事件
$('#AddBtn').on('click', function () {
t1_sid.style.display = 'block';// 显示选择的元素---将sid显示出来
//页面层
var addLay = layer.open({
type: 1 //Page层类型
, skin: 'layui-layer-molv'
, area: ['700px', '430px']
, title: ['新增学生信息', 'font-size:18px']
, btn: ['保存', '取消']
, shadeClose: true
, shade: 0 //遮罩透明度
// , maxmin: true //允许全屏最小化
, content: $("#AddFormDiv")
@* , success: function () {
$("#AddForm")[0].reset();
}*@
, success: function (layero,index) {
$("#AddForm")[0].reset();
//弹出层---进行校验1、将弹出层的确定按钮 转为layui的form提交按钮 2、写自定义的校验规则 3、通过from.on实现
//1.1 条件form标识
layero.addClass('layui-form');
//1.2 将保存按钮转为提交按钮
layero.find('.layui-layer-btn0').attr({
'lay-filter': 'formButton',
'lay-submit':''
})
}
, yes: function () {//yes表示定义的第一个按钮
//3.1 点击form表单的 "提交"按钮,会先进行自定义的校验
form.on('submit(formButton)', function () {
var stu = {};
var Sid = $("#Sid").val();
var Name = $("#Name").val();
var ClassName = $("#ClassName").val();
var ProfessionalName = $("#ProfessionalName").val();
var Birthday = $("#Birthday").val();
var Sex = $("#Che input[name='Sex']:checked").val();
stu.Sid = Sid;
stu.Name = Name;
stu.ClassName = ClassName;
stu.ProfessionalName = ProfessionalName;
stu.Birthday = Birthday;
stu.Sex = Sex;
console.log(stu);
// alert(JSON.stringify(stu));
$.ajax({
url: '/Student/Add',
data: {
param: JSON.stringify(stu)
},
type: 'Post',
success: function (res) {
if (res.code === 0) {
layer.close(addLay);//关闭当前窗口
//弹出消息框
// layer.alert(res.msg);
layer.msg(res.msg, {
icon: 1,
time: 1500 //1.5秒关闭(如果不配置,默认是3秒)
}, function () {
//当前数据进行刷新,新增内容清空
table.reload('test');
});
}
else {
layer.msg(res.msg, { icon: 2 });
}
$("#AddForm")[0].reset();
}
})
})
}
, btn2: function () {
$("#AddForm")[0].reset();
}
});
});
});
</script>
</body>
</html>
五、部分参考
1、Layui官网
http://layui.winxapp.cn/doc/index.html
2、日期格式:
1) https://www.developer.com/microsoft/dealing-with-json-dates-in-asp-net-mvc/
2) https://blog.csdn.net/fangyuan621/article/details/117436917
3、弹出层校验前端数据格式
https://blog.csdn.net/weixin_44427181/article/details/126154909
更多推荐
所有评论(0)