ASP.NET MVC +EASYUI TreeGrid +EF 菜单管理
小白所写,不喜勿喷
借鉴了诸多大神的帖子
特别提示:
1.对数据库的操作采用了ef ,如果对ef不了解可以百度了解一下
2.easyui Treegrid的 本项目是 分多步进行加载 第一次加载根目录,点击展开加载子目录
3.TreeGrid 的分页只对 根目录 子节显示全部
4.返回给视图对象中的属性 state用来显示节点是文件图案:还是节点符号 :
也是easyui 规定的属性 "close"为文件夹 "open"为 普通节点
5._parentId 是easyui用来判定 父子关系的凭证 的属性 会依靠这个属性自己找到对应的节
完成图:
控制器:
public class MenuController : Controller
{
// GET: Menu
#region 查
public ActionResult Index(int? id ,int rows=5,int page=1)
{
if (id==null)//如果是第一次加载
{
return View();
}
else if (id==0)//如果是加载根目录
{
using (SingleEntities db = new SingleEntities())
{
var res = (from v in db.popedom
where v.popedomfatherid == 0
select new
{
popedomid = v.popedomid,
popedomname = v.popedomname,
popedomurl = v.popedomurl,
_parentId = v.popedomfatherid,
state = db.popedom.FirstOrDefault(x=>x.popedomfatherid== v.popedomid)==null?"open":"closed"
})
.OrderByDescending(x=>x.popedomid)
.Skip(rows * (page - 1))//剔除前面多少个
.Take(rows)//取前面多少个
.ToArray();
var total = (from n in db.popedom where n.popedomfatherid == 0 select n).Count();
var json = new { total = total, rows = res };
return Json(json, JsonRequestBehavior.AllowGet);
}
}
else//加载子集
{
using (SingleEntities db = new SingleEntities())
{
var res1 = (from v in db.popedom
where v.popedomfatherid == id
select new
{
popedomid = v.popedomid,
popedomname = v.popedomname,
popedomurl = v.popedomurl,
_parentId = v.popedomfatherid,
state = db.popedom.FirstOrDefault(x => x.popedomfatherid == v.popedomid) == null ? "open" : "closed"
}).ToArray();
var json = new { total = res1.Count(), rows = res1 };
return Json(json, JsonRequestBehavior.AllowGet);
}
}
}
#endregion
#region 增
public ActionResult AddMenu()
{
popedom model = new popedom();
model.popedomname = Request.Form["name"];
model.popedomurl = Request.Form["url"];
model.popedomfatherid= int.Parse(Request.Form["fatherid"]);
using (SingleEntities db=new SingleEntities())
{
db.popedom.Add(model);
var obj= db.SaveChanges();
var retmsg = new {
issuccess = true,
msg = "成功添加" + obj + "条数据"
};
return Json(retmsg,JsonRequestBehavior.AllowGet);
}
}
#endregion
#region 删
public ActionResult DeleteMenu()
{
int id= int.Parse(Request.Form["id"]);
try
{
using (var db = new SingleEntities())
{
var res = db.popedom.FirstOrDefault(x => x.popedomid == id);
db.popedom.Remove(res);
var obj = db.SaveChanges();
var msg = new
{
issuccess = true,
msg = "删除成功,删除了" + obj + "条数据"
};
return Json(msg, JsonRequestBehavior.AllowGet);
}
}
catch (Exception)
{
var msg = new
{
issuccess = false,
msg = "删除失败"
};
return Json(msg, JsonRequestBehavior.AllowGet);
}
}
#endregion
#region 改
public ActionResult UpdateMenu()
{
var popedomname = Request.Form["popedomname"];
var popedomurl= Request.Form["popedomurl"];
int id=int.Parse(Request.Form["popedomid"]);
try
{
using (var db = new SingleEntities())
{
var res = db.popedom.FirstOrDefault(x => x.popedomid == id);
res.popedomname = popedomname;
res.popedomurl = popedomurl;
var obj = db.SaveChanges();
var retmsg = new
{
issuccess = true,
msg = "成功修改" + obj + "条数据"
};
return Json(retmsg, JsonRequestBehavior.AllowGet);
}
}
catch (Exception)
{
var retmsg = new
{
issuccess = false,
msg = "修改失败!"
};
return Json(retmsg, JsonRequestBehavior.AllowGet);
}
}
#endregion
}
cshtml视图:
@{
Layout=null;
}
<!Doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>菜单</title>
@Styles.Render("~/Scripts/jquery-easyui-1.4.1/themes")
@Scripts.Render("~/Scripts/jquery-easyui-1.4.1")
<script>
//treegrid初始化
$(function ()
{
$('#w').window('close')
$('#tt').treegrid({
url:'@Url.Action("Index","Menu")',
idField: 'popedomid',
treeField: 'popedomname',
width:1120,
method: 'Post',
pagination: true,
lines: true,
rownumbers:true,
pageSize: 5,
pageList: [5, 10, 20],
onBeforeLoad: function (row, param)//加载数据前触发
{
if (!row)
{
param.id = 0;
}
else
{
param.id = row.popedomid;
}
},
columns: [[
{ title: '菜单名称', field: 'popedomname', width: 300, align: 'left', editor: { type: 'validatebox', options: { required: true } } },
{ title: '编号', field: 'popedomid', width: 300, align: 'center'},
{ title: '地址', field: 'popedomurl', width: 400, align: 'center', editor: { type: 'validatebox', options: { required: true } } },
]],
toolbar: [
{
text: '添加根目录', iconCls: 'icon-add', handler: function () {
$('#w').window('open');
$("#father").show();
$("#child").hide();
}
}, '-',
{
text: '添加子菜单', iconCls: 'icon-add', handler: function () {
var node = $('#tt').treegrid('getSelected');
if (node) {
$('#w').window('open');
$("#father").hide();
$("#child").show();
}
else
{
$.messager.alert('提示','未选中行无法添加子节点','info')
}
}
}, '-',
{
text: '删除', iconCls: 'icon-remove', handler: function () {
remove();
}
}, '-',
{
text: '编辑', iconCls: 'icon-edit', handler: function () {
edit();
}
}, '-',
{
text: '取消编辑', iconCls: 'icon-undo', handler: function () {
cancelEdit();
}
}, '-',
{
text: '保存', iconCls: 'icon-save', handler: function () {
save();
}
}, '-',
{
text: '刷新', iconCls: 'icon-reload', handler: function () {
query();
}
}, '-']
});
})
//treegrid初始化
var editingId
//增
function append(type)
{
if ($("#name").val() == "" || $("#url").val()=="") {
$.messager.alert("提示", "不能为空", "info")
return
}
var node = $('#tt').treegrid('getSelected');
$.ajax({
url: '@Url.Action("AddMenu", "Menu")',
type: 'post',
data: {
name: $("#name").val(),
url: $("#url").val(),
fatherid: type=='child'? node.popedomid:0
},
success: function (res) {
if (res.issuccess) {
$.messager.alert("提示", res.msg, "info")
$("#tt").treegrid("reload");
$('#w').window('close');
}
else {
$.messager.alert("提示", res, "error")
}
},
error: function (err) { }
})
}
//删
function remove()
{
var node = $('#tt').treegrid('getSelected');
if (!node) {
// $('#tg').treegrid('remove', node.id);
$.messager.alert("提示", '请选中一行进行删除操作', 'info')
return
}
$.messager.confirm('提示', '删除后无法恢复,确定删除?', function (r) {
if (r) {
$.ajax({
url:'@Url.Action("DeleteMenu","Menu")',
type: 'post',
data: { id: node.popedomid},
success: function (res)
{
if (res.issuccess)
{
$('#tt').treegrid('remove', node.popedomid);
$.messager.alert("提示", res.msg, 'info')
}
else
{
$.messager.alert("提示", res.msg, 'info')
}
},
error: function (err) {
$.messager.alert("提示", '删除失败', 'info')
}
})
}
},
"warning"
)}
//改
function edit() {
if (editingId != undefined)
{
cancelEdit();
}
var row = $('#tt').treegrid('getSelected');
if (row) {
editingId = row.popedomid
$('#tt').treegrid('beginEdit', editingId);
}
}
//保存
function save() {
if (editingId != undefined) {
var row = $('#tt').treegrid('find', editingId);
$.ajax({
url:'@Url.Action("UpdateMenu", "Menu")',
type: 'post',
data: row,
success: function (res)
{
if (res.issuccess) {
$.messager.alert("提示", res.msg, 'info')
$('#tt').treegrid('endEdit', editingId);
editingId = undefined;//清除值
}
else
{
$.messager.alert("提示", '修改失败', 'info')
}
},
error: function (err)
{
}
})
}
else {
$.messager.alert("提示", '没有正在编辑的行', 'info')
}
}
//取消编辑
function cancelEdit()
{
if (editingId != undefined)
{
$('#tt').treegrid('endEdit', editingId);
editingId = undefined;//清除值
}
}
</script>
</head>
<body>
<div>
<table id="tt" ></table>
<div id="add"></div>
<div id="modify"></div>
<div id="remove"></div>
</div>
<div id="w" class="easyui-window" title="添加新项" data-options="iconCls:'icon-save'" style="width:280px;height:140px;padding:5px;">
<form>
<table>
<tr>
<td>菜单名称:</td>
<td><input id="name" naem="name" class="easyui-textbox" type="text" data-options="required:true"/></td>
</tr>
<tr>
<td>访问路径:</td>
<td><input id="url" naem="url" class="easyui-textbox" type="text" data-options="required:true"/></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
<div style="text-align:center;padding:5px">
<a href="javascript:void(0)" id="father" class="easyui-linkbutton" οnclick="return append('father')">保存</a>
<a href="javascript:void(0)" id="child" class="easyui-linkbutton" οnclick="return append('child')">保存</a>
<a href="javascript:void(0)" class="easyui-linkbutton" οnclick="clearForm()">重置</a>
</div>
</form>
</div>
</body>
</html>
sqlserver表:
popedomid 主键自增长