1.根据上一篇博客我们接着写
我们在百度上找到layui框架放到我们的项目中去,引用js和css
2.在layui事例里面早到相关代码
<table class="layui-hide" id="demo" lay-filter="test"></table>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
<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>
3.在控制器这样写
/// <summary>
///增加
/// </summary>
/// <returns></returns>
public JsonResult AddAdmin(AdminInfo adminUser)
{
Ajaxs ajaxs = new Ajaxs();
ajaxs.Success = adminUserService.Add(adminUser);
return Json(ajaxs);
}
/// <summary>
///修改
/// </summary>
/// <returns></returns>
public JsonResult Updatedmin(AdminInfo adminUser)
{
Ajaxs ajaxs = new Ajaxs();//LoginName,Telphone,Email,RoleId,Remark
ajaxs.Success = adminUserService.Update(new AdminInfo() { AdminId = adminUser.AdminId, LoginName = adminUser.LoginName, Telphone = adminUser.Telphone, Email = adminUser.Email, RoleId = adminUser.RoleId , Remark = adminUser.Remark });
return Json(ajaxs);
}
/// <summary>
///删除
/// </summary>
/// <returns></returns>
public JsonResult DeleteAdmin(int AdminId)
{
Ajaxs ajaxs = new Ajaxs();
AdminInfo adminUser = adminUserService.Query(a=>a.AdminId== AdminId);
ajaxs.Success = adminUserService.Delete(adminUser);
return Json(ajaxs);
}
public ActionResult Logic()
{
if (Models.UserContext.userContext.adminUser != null)
{
return RedirectToAction("Index", "Home");
}
var cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
//获取存在的cookie
var ticket = FormsAuthentication.Decrypt(cookie.Value);
string userData = ticket.UserData;
if (!string.IsNullOrEmpty(userData))
{
//存储在session里面
AdminInfo user = new AdminInfo();
user.AdminId = Convert.ToInt32(userData.Split('#')[0]);
user.LoginName = userData.Split('#')[1];
Models.UserContext.userContext.adminUser = user;
return RedirectToAction("Index", "Home");
}
}
return View();
}
/// <summary>
/// 修改状态
/// </summary>
/// <param name="AdminId"></param>
/// <param name="zhuangTai"></param>
/// <returns></returns>
public JsonResult UpdateState(int AdminId,int zhuangTai) {
Ajaxs ajaxs = new Ajaxs();
AdminInfo adminInfo = adminUserService.Query(a=>a.AdminId== AdminId);
adminInfo.zhuangTai = zhuangTai;
ajaxs.Success = adminUserService.Update(adminInfo);
return Json(ajaxs);
}
/// <summary>
/// 批量删除
/// </summary>
/// <returns></returns>
public JsonResult AllDeleteById(string AdminId)
{
string[] arr1 = AdminId.Split(',');
int[] inArray = Array.ConvertAll<string, int>(arr1, s => int.Parse(s));
Ajaxs ajaxs = new Ajaxs();
ajaxs.Success = adminUserService.AllDeleteById(inArray);
return Json(ajaxs);
}
4.页面上的代码是
<script>
/*提交按钮*/
$("#Update_Administrator").on("click", function () {
var data = {};
data.AdminId = $("#ID").val();
data.LoginName = $("#LoginName").val();
// data.Sex = $("input[name='form-field-radio']:checked").val();
data.Telphone = $("#Telphone").val();
data.Email = $("#Email").val();
data.Remark = $("#Remark").val();
data.RoleId = $("#RoleId").val();
$.ajax({
type: "post",
url: "/Home/Updatedmin",
data: data,
async: false,
success: function (data) {
if (data.Success) {
layer.alert('修改成功!', {
title: '提示框',
icon: 1,
});
} else {
layer.alert('修改失败!', {
title: '提示框',
icon: 1,
});
}
}
});
});
//条件查询按钮
$("#btn_search").click(function () {
var table = layui.table;
var LoginName = $("#LoginName").val();
var CreateTime = $("#start").val();
table.reload('sample_table', {
where: {
LoginName: LoginName,
CreateTime: CreateTime
}
});
});
//表格数据加载
layui.use(['table', 'util'], function () {
//用table就要定义
var table = layui.table;
//用form就要定义
var form = layui.form;
//表格数据加载
table.render({
elem: '#sample_table' //表格id要对应
, url: '/Home/ListAdminInfo' //对应控制器的action方法
, height:300
, page: true //开启分页
, cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
, cols: [[
{ type: 'checkbox' } //开启复选框
,{ field: 'AdminId', title: 'ID', sort: true ,hide:true}
, { field: 'LoginName', title: '用户名' } //width 支持:数字、百分比和不填写。你还可以通过 minWidth 参数局部定义当前单元格的最小宽度,layui 2.2.1 新增
, { field: 'Telphone', title: '电话', sort: true }
, { field: 'Email', title: '邮箱' }
, { field: 'Remark', title: '备注' }
, { field: 'RoleId', title: '角色ID' }
, { field: 'zhuangTai', title: '状态', width: 120, templet: '#switchTpl', unresize: true } //切换按钮禁用启用
, { field: 'CreateTime', title: '添加时间', width: 120, templet: '<div> {{Format(d.CreateTime,"yyyy-MM-dd")}}</div>' }
, { title: '操作',fixed: 'right', width: 200, align: 'center', toolbar: '#barDemo' }
]]
});
//监听启用和禁用操作
form.on('switch(sexDemo)', function (obj) {
var tip = "启用";
var id = this.value;
alert(id);
//获取当前选中的值
var status = this.name;
alert(status);
if (this.value === "1") {
tip = "停用";
status = 0;
}
else {
status = 1;
}
//启用的功能代码
layer.confirm('真的要' + tip + '吗', function (index) {
$.ajax({
url: "/Home/UpdateState?AdminId=" + id + "&zhuangTai=" + status,
type: "Post",
success: function (data) {
if (data.Success) {
layer.msg(tip+'成功!', {
title: '提示框',
icon: 1,
time: 1000
}, function () {
TableReload();
layer.close(index);
});
}
else {
layer.msg(tip +'失败!', {
title: '提示框',
icon: 1,
time: 1000
});
}
}
});
});
});
//监听工具条
table.on('tool(demo)', function (obj) {
var data = obj.data;
var AdminId = data.AdminId;
if (obj.event === 'del') {
//删除的功能代码
layer.confirm('真的要删除吗', function (index) {
$.ajax({
url: "/Home/DeleteAdmin?AdminId=" + AdminId,
type: "Post",
success: function (data) {
if (data.Success) {
layer.msg('删除成功!', {
title: '提示框',
icon: 1,
time: 1000
}, function () {
TableReload();
layer.close(index);
});
obj.del();
}
else {
layer.msg('删除失败!', {
title: '提示框',
icon: 1,
time: 1000
});
}
}
});
});
} else if (obj.event === 'edit') {
$("#test").val(data.LoginName);
$("#Telphone").val(data.Telphone);
$("#Email").val(data.Email);
$("#Remark").val(data.Remark);
$("#RoleId").val(data.RoleId);
$("#ID").val(data.AdminId);
layer.open({
type: 1,
title: '添加管理员',
area: ['500px', ''],
shadeClose: false,
content: $('#add_administrator_style'),
});
}
});
//监听表格复选框选择
table.on('checkbox(demo)', function (obj) {
});
//监听复选框
var $ = layui.$, active = {
getCheckLength: function () {
//获取选中数据
var checkStatus = table.checkStatus('sample_table')
, data = checkStatus.data;
//获取拼接的id
var id = BatchDelete(data);
//删除数据
layer.confirm('真的要删除吗', function (index) {
$.ajax({
url: "/Home/AllDeleteById?AdminId=" + id,
type: "Post",
success: function (data) {
if (data.Success) {
window.location.reload();
layer.msg('删除成功!', {
title: '提示框',
icon: 1,
time: 2000
}, function () {
TableReload();
layer.close(index);
});
}
else {
layer.msg('删除失败!', {
title: '提示框',
icon: 1,
time: 2000
});
}
}
});
});
}
};
//点击批量删除按钮事件
$('#deleteBatch').on('click', function () {
alert("进入");
var type = $(this).data('type');
active[type] ? active[type].call(this) : '';
});
});
//拼接id
function BatchDelete(data) {
var id = "";
for (var i = 0; i < data.length; i++)
{
if (i != data.length - 1) {
id += data[i].AdminId + ',';
}
else {
id += data[i].AdminId;
}
}
return id;
}
//转换时间
function Format(datetime, fmt) {
var newtime = datetime.replace(/\/Date\((\d+)\)\//gi, "$1");
if (parseInt(newtime) == newtime) {
if (newtime.length == 10) {
newtime = parseInt(newtime) * 1000;
} else if (newtime.length == 13) {
newtime = parseInt(newtime);
}
}
newtime = new Date(newtime);
var o = {
"M+": newtime.getMonth() + 1, //月份
"d+": newtime.getDate(), //日
"h+": newtime.getHours(), //小时
"m+": newtime.getMinutes(), //分
"s+": newtime.getSeconds(), //秒
"q+": Math.floor((newtime.getMonth() + 3) / 3), //季度
"S": newtime.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (newtime.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
</script>
<script type="text/html" id="barDemo">
<!-- <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a> -->
<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 type="text/html" id="switchTpl">
<!-- 这里的 checked 的状态只是演示 -->
<input type="checkbox" name="{{d.zhuangTai}}" value="{{d.AdminId}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="sexDemo" {{ d.zhuangTai == 1 ? 'checked' : ' ' }} />
</script>
<script type="text/javascript">
jQuery(function ($) {
var oTable1 = $('#sample_table').dataTable({
"aaSorting": [[1, "desc"]],//默认第几个排序
"bStateSave": true,//状态保存
"aoColumnDefs": [
//{"bVisible": false, "aTargets": [ 3 ]} //控制列的隐藏显示
{ "orderable": false, "aTargets": [0, 2, 3, 4, 5, 7, 8,] }// 制定列不参与排序
]
});
$('table th input:checkbox').on('click', function () {
var that = this;
$(this).closest('table').find('tr > td:first-child input:checkbox')
.each(function () {
this.checked = that.checked;
$(this).closest('tr').toggleClass('selected');
});
});
$('[data-rel="tooltip"]').tooltip({ placement: tooltip_placement });
function tooltip_placement(context, source) {
var $source = $(source);
var $parent = $source.closest('table')
var off1 = $parent.offset();
var w1 = $parent.width();
var off2 = $source.offset();
var w2 = $source.width();
if (parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2)) return 'right';
return 'left';
}
});
</script>