.net+EF+mvc通过EasyUI的DataGrid实现增删改查
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" type="text/css" href="~/Scripts/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="~/Scripts/themes/icon.css">
@*<link rel="stylesheet" type="text/css" href="~/Scripts/demo.css">*@
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.easyui.min.js"></script>
<script src="~/Scripts/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">
$(function () {
$('#dg').datagrid({
url: '/Main/FenYe1',
loadMsg: '请稍等,正在拼命加载...',
fitColumns: false,//防止水平滚动
rownumbers: true, //是否加行号
pagination: true, //是否显式分页
pageSize: 5, //页容量,必须和pageList对应起来,否则会报错
pageNumber: 1, //默认显示第几页
pageList: [5, 10, 15],//分页中下拉选项的数值
checkOnSelect: true,
selectOnCheck: true,
//固定列
frozenColumns: [[
{
field: 'id', title: '请选择..', width: 58, align: 'center',
checkbox: true
},
{ field: 'name', title: '名称', width: 100 },
]],
//非固定列
columns: [[
{ field: 'sex', title: '性别', width: 100 },
{ field: 'age', title: '年龄', width: 100 },
{ field: 'dataTime', title: '记录时间', width: 150, align: 'center' },
{ field: 'content', title: '个人介绍', width: 250, align: 'left' },
]],
//导航栏('-')表示'|'分隔符
toolbar: [
{ text: '增加', iconCls: 'icon-add', handler: function () { addStu(); } }, '-',
{ text: '修改', iconCls: 'icon-edit', handler: function () { edittbUser(); } }, '-',
{ text: '删除', iconCls: 'icon-remove', handler: function () { deleteUser(); } }, '-',
{ text: '查看', handler: function () { } }, '-',
{ text: '刷新', iconCls: 'icon-reload', handler: function () { deviceInfoRefreshClick(); } }, '-',
{ text: '导出', iconCls: 'icon-save', handler: function () { $(dg).treegrid('reload'); } }, '-'],
});
});
//添加
function addStu() {
$("#j_addStu").dialog({
title: "新添学生1",
width: 500,
height: 450,
href: '/Main/Add_View',
buttons: [{
text: '新增',
handler: function () {
add();
}
},{
text:'关闭',
handler: function () {
$('#j_addStu').dialog('close');
}
}],
});
}
function add() {
//是一个验证表单的功能。当validate()这个函数返回值是true的时候,表单提交,反之则不提交。
$("#addForm").form('submit', {
url: '/Main/AddStu',
onSubmit: function () {
return $(this).form('validate');
},
success: function (data) {
if (data == 'ok') {
$.messager.show({
title: 'success',
msg: '插入成功!'
});
// $(dialogId).dialog('close');
$('#dg').datagrid('reload');
} else {
$.messager.show({
title: 'Error',
msg: '插入失败!'
});
}
//$(dialogId).dialog('close');
$('#dg').datagrid('reload');
}
});
}
// 删除代码部分
function deleteUser() {
var row = $('#dg').datagrid('getChecked');
if (row) {
//id字符串
var idsStr = "";
var arr = new Array();
for (var i = 0; i < row.length; i++) {
//必须设置它为局部变量,否则会出现多条重复数据
var map = {};
map["id"] = row[i].id;
arr[i] = map;
}
for (var i = 0; i < arr.length; i++) {
idsStr += arr[i].id + ",";
}
if (idsStr.length > 0) {
idsStr = idsStr.substr(0, idsStr.length - 1);
}
$.messager.confirm('删除提示', '确定要删除吗', function (r) {
if (r) {
$.post('/Main/DelStu', { "idsStr": idsStr }, function (data, status) {
if (data == "ok") {
$.messager.show({
title: 'success',
msg: '删除成功!'
});
$('#dg').datagrid('reload');
} else {
$.messager.show({
title: 'Error',
msg: '删除用户失败!'
});
}
});
}
});
}
else {
//$.messager.show({
// title: 'Error',
// msg: '你没有选中行!'
//});
$.messager.alert("提示", "您没有选中任何行!");
}
}
//编辑
function edittbUser() {
$("#edittbStuDialog").dialog({
title: "修改信息1",
width: 500,
height: 450,
//href: '/Main/Update_View',
buttons: [{
text: '修改',
handler: function () {
edit();
}
}, {
text: '关闭',
handler: function () {
$('#edittbStuDialog').dialog('close');
}
}],
});
//getSelected返回第一个被选中的行或如果没有选中的行则返回null。
var row = $('#dg').datagrid('getSelected');
if (row) {
$("#editForm").form('load', {
name:row.name,
sex:row.sex,
age:row.age,
content:row.content
});
url = '/Main/UpdateStu?id=' + row.id;
}
else {
$('#edittbStuDialog').dialog('close');
$.messager.alert("提示", "您没有选中任何行!");
}
}
function edit() {
$("#editForm").form('submit', {
url:url,
onSubmit: function () {
// alert(formId);
return $(this).form('validate');
},
success: function (data) {
if (data == 'ok') {
$.messager.show({
title: 'success',
msg: '修改成功!'
});
$("#edittbStuDialog").dialog('close');
$('#dg').datagrid('reload');
} else {
$.messager.show({
title: 'Error',
msg: '修改失败!'
});
}
//$(dialogId).dialog('close');
$('#ReceiveList').datagrid('reload');
}
});
}
</script>
</head>
<body>
<table id="dg" style="width:700px;height:800px;"></table>
@*data-options="required:true"自动验证:此输入项为必填项*@
@*增加class="easyui-dialog"自定义弹出框*@
<div id="j_addStu" style="padding:10px 20px"></div>
@*修改*@
<div id="edittbStuDialog" style="padding:10px 20px; display:none">
<form id="editForm" method="post">
<table class="align-center">
<tr>
<td>学生名</td>
<td><input name="name" class="easyui-validatebox" type="text" /></td>
</tr>
<tr>
<td>性别</td>
<td><input name="sex" class="easyui-validatebox" type="text" /></td>
</tr>
<tr>
<td>年龄</td>
<td><input name="age" class="easyui-validatebox" type="text" /></td>
</tr>
<tr>
<td>个人介绍</td>
<td><textarea rows="5" class="easyui-validatebox" cols="19" name="content"></textarea></td>
</tr>
</table>
</form>
</div>
</body>
</html>
MainController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using System.Data.Entity.Migrations;
namespace DataGrid_01.Controllers
{
public class MainController : Controller
{
DbContext db = new TestEntities();
//DbContextFactory dbcontext = new DbContextFactory();
//TestEntities db = dbcontext.GetDbContext();
#region 01-主页面
/// <summary>
/// 01-主页面
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
return View();
}
#endregion
#region 02-进行分页操作
/// <summary>
/// 02-分页
/// </summary>
/// <param name="rows">每页显示的记录数</param>
/// <param name="page">页码,显示第几页</param>
/// <returns></returns>
public ActionResult FenYe1(int rows, int page)
{
try
{
var Stu_List = db.Set<student>().OrderByDescending(a => a.dataTime).Skip(rows * (page - 1)).Take(rows).ToList();
var json = new
{
total = db.Set<student>().Count(),
rows = (from r in Stu_List
select new
{
id = r.id,
name = r.name,
sex = r.sex,
age = r.age,
dataTime = r.dataTime.ToString(),
content = r.content,
}).ToList(),
};
return Json(json);
}
catch (Exception ex)
{
FileOperateHelp.WriteFile("E:/ErrorLog333.txt", ex.Message);
return Content("error");
}
}
#endregion
#region 03-增加操作
/// <summary>
/// 03-增加操作
/// </summary>
/// <param name="name">学生姓名</param>
/// <param name="sex">性别</param>
/// <param name="age">年龄</param>
/// <param name="content">个人介绍</param>
/// <returns></returns>
public ActionResult AddStu(string name, string sex, string age, string content)
{
try
{
student stu = new student()
{
id = Guid.NewGuid().ToString("N"),
name = name,
sex = sex,
age = age,
content = content,
dataTime = DateTime.Now,
};
db.Entry(stu).State = EntityState.Added;
int count = db.SaveChanges();
if (count > 0)
{
return Content("ok");
}
else
{
return Content("error");
}
}
catch (Exception ex)
{
FileOperateHelp.WriteFile("E:/ErrorLog333.txt", ex.Message);
return Content("error");
}
}
#endregion
#region 04-删除
/// <summary>
/// 04-删除
/// </summary>
/// <param name="id">id</param>
/// <returns></returns>
public ActionResult DelStu(string idsStr)
{
try
{
string[] str = idsStr.Split(new char[] { ',' });
//int[] str_int = Array.ConvertAll(str, int.Parse);
foreach (var item in str)
{
var del = db.Set<student>().Where(a => a.id == item).FirstOrDefault();
db.Entry<student>(del).State = EntityState.Deleted;
}
int count = db.SaveChanges();
if (count > 0)
{
return Content("ok");
}
else
{
return Content("error");
}
}
catch (Exception ex)
{
FileOperateHelp.WriteFile("E:/ErrorLog333.txt", ex.Message);
return Content("error");
}
}
#endregion
#region 05-修改
/// <summary>
/// 05-修改
/// </summary>
/// <param name="id">id</param>
/// <param name="name">学生名</param>
/// <param name="sex">性别</param>
/// <param name="age">年龄</param>
/// <param name="content">个人介绍</param>
/// <returns></returns>
public ActionResult UpdateStu(string id, string name, string sex, string age, string content)
{
try
{
var stuList = db.Set<student>().Where(a => a.id == id).FirstOrDefault();
stuList.name = name;
stuList.sex = sex;
stuList.age = age;
stuList.dataTime = DateTime.Now;
stuList.content = content;
db.Entry(stuList).State = EntityState.Modified;
int count = db.SaveChanges();
if (count > 0)
{
return Content("ok");
}
else
{
return Content("error");
}
}
catch (Exception ex)
{
FileOperateHelp.WriteFile("E:/ErrorLog333.txt", ex.Message);
return Content("error");
}
}
#endregion
#region 06-修改页面
/// <summary>
/// 06-修改页面
/// </summary>
/// <returns></returns>
public ActionResult Update_View()
{
return View();
}
#endregion
//增加页面
public ActionResult Add_View() {
return View();
}
}
}
作者:chenze 出处:https://www.cnblogs.com/chenze-Index/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |