ASP.NET MVC +EF+Easyui datagrid
先看下效果图: 前台View页面跟之前的ASP.NET WebForm 差不多,只需要把post提交请求的路径改成/控制器/动作,绑定的参数改动下,开看源码:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Index</title>
<link href="../../Content/Easyui/themes/default/easyui.css" rel="stylesheet" type="text/css" />
<link href="../../Content/Easyui/themes/icon.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.easyui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
grid();
});
function grid() {
$("#tabs").datagrid({
width: 600, //宽度
height: 400, //高度
singleSelect: true, //选中一行的设置
rownumbers: true, //行号
url: "/Home/Query", //请求路径
title: "学员信息", //标题
iconCls: "icon-save", //图标
collapsible: true, //隐藏按钮
//冻结列
frozenColumns: [[{ field: "chk", "checkbox": true}]],
//列
columns: [[
{ field: "NO", title: "编号", width: 80 },
{ field: "NAME", title: "姓名", width: 100 },
{ field: "pwd", title: "密码", width: 100 },
{ field: "sex", title: "性别", width: 100 },
{ field: "age", title: "年龄", width: 100 },
{ field: "ADDRESS", title: "住址", width: 100 }
]],
pagination: true,
toolbar: [{
id: "btnadd",
text: "添加",
iconCls: "icon-add",
handler: function () {
$("#btnsave").linkbutton("enable");
add_dg();
}
},
{
id: "btnEdit",
text: "编辑",
iconCls: "icon-edit",
handler: function () {
$("#btnsave").linkbutton("enable");
edit_dg();
}
},
{
id: "btncut",
text: "删除",
iconCls: "icon-no",
handler: function () {
$("#btnsave").linkbutton("enable");
delete_dg();
}
}
]
}); //////////////////////////////分页/////////////////////////////
$("#tabs").datagrid('getPager').pagination({
beforePageText: "第",
afterPageText: "页",
displayMsg: "当前 {from} - {to}条数据 共{total} 条数据",
pageSize: 10,
pageList: [5, 10, 15, 20, 30]
});
}
/////////////////删除///////////
function delete_dg() {
var selected = $("#tabs").datagrid('getSelected');
if (selected != null) {
$.messager.confirm('提示', '是否确定要删除?', function(y) {
if (y) {
var v = "";
var checked = $("#tabs").datagrid('getChecked');
$.each(checked, function(i, j) {
v += j.id + ",";
});
v = v.substring(0, v.length - 1);
$.post("/Home/Del", {"id": v }, function(data) {
$.messager.alert('提示', data);
$("#tabs").datagrid('reload');
});
}
});
} else {
$.messager.alert('提示', '您还没有选中一行数,请选中在删除!');
}
}
//////////////////添加///////////////////
function add_dg() {
//表单清空
$("#fm_dg")[0].reset();
//显示
$("#dd_dg").show();
//以窗体的形式展示
$("#dd_dg").dialog({
title: "添加学员信息", //标题
iconCls: "icon-add", //图标
width: 300, //窗体的宽度
height: 200, //窗体的高度
modal: true, //遮罩层
//按钮集合
buttons: [
{
text: "添加", //添加按钮的文本值
iconCls: "icon-ok", //添加按钮的图标
handler: function () {
//将数据序列化
var parm = $("#fm_dg").serialize();
//中文格式转换
var pp = decodeURIComponent(parm, true);
//post异步提交
$.post("/Home/Add", { data: pp }, function (data) {
$.messager.alert('提示', data);
//重新加载datagrid
$("#tabs").datagrid('reload');
//关闭
$("#dd_dg").window('close');
});
}
},
{
text: "取消",
iconCls: "icon-cancel",
handler: function () {
$("#dd_dg").window("close");
}
}
]
});
}
/////////////////修改//////////////////
function edit_dg() {
//选中一行,获取这一行的属性的值
var selected = $("#tabs").datagrid('getSelected');
//判断是否选中
if (selected != null) {
$("#id").val(selected.id);
$("#no").val(selected.NO);
$("#name").val(selected.NAME);
$("#pwd").val(selected.pwd);
//取值显示性别
if (selected.sex == "男") {
$("#sex option").eq(0).attr("selected", "selected");
} else {
$("#sex option").eq(1).attr("selected", "selected");
}
$("#age").val(selected.age);
$("#address").val(selected.ADDRESS);
$("#dd_dg").show(); //显示修改窗体
$("#dd_dg").dialog({
title: "编辑信息",
iconCls: "icon-edit",
modal: true, //遮罩层
width: 300,
height: 200,
buttons: [
{
text: "编辑",
iconCls: "icon-edit",
handler: function () {
var parm = $("#fm_dg").serialize();
var pp = decodeURIComponent(parm, true);
$.post("/Home/Edit", { data: pp }, function (data) {
$.messager.show({
title: "提示",
msg: data
});
$("#tabs").datagrid("reload");
$("#dd_dg").window("close");
});
}
},
{
text: "取消",
iconCls: "icon-cancel",
handler: function () {
$("#dd_dg").window('close');
}
}
]
});
} else {
$.messager.alert('提示', '请选中一行在进行编辑');
}
}
</script>
</head>
<body>
<table id="tabs"></table>
<div id="dd_dg" style="display:none;" >
<form id="fm_dg" method="post">
<input type="hidden" name="id" id="id"/>
编号:<input type="text" name="no" id="no" class="easyui-validatebox" required="true" missingMessage="用户编号不能为空!"/><br/>
姓名:<input type="text" name="name" id="name" class="easyui-validatebox" required="true" missingMessage="用户姓名不能为空!"/><br/>
密码:<input type="password" name="pwd" id="pwd" class="easyui-validatebox" required="true" missingMessage="用户密码不能为空!"/><br/>
性别:<select name="sex" id="sex">
<option value="1">男</option>
<option value="0">女</option>
</select><br/>
年龄:<input type="text" name="age" id="age" class="easyui-validatebox" required="true" missingMessage="用户年龄不能为空!"/><br/>
住址:<input type="text" name="address" id="address" class="easyui-validatebox" required="true" missingMessage="用户住址不能为空!"/><br/>
</form>
</div>
</body>
</html>
控制器里面写的要跟之前的一般处理页面有所区别,你会发现这里没有用sql语句
public class HomeController : Controller
{
readonly studentEntities _db=new studentEntities();
// GET: /Home/
public ActionResult Index()
{
return View();
}
//显示的方法
public ActionResult Query()
{
int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
int pageSize = Request["rows"] == null ? 1 : int.Parse(Request["rows"]);
var temp = (from c in _db.stu orderby c.id select c).Skip(pageSize*(pageIndex - 1)).Take(pageSize).ToList();
var data = from a in temp select new {a.id,a.NO,a.NAME,a.pwd,a.sex,a.age,a.ADDRESS};
var rult = new{total=_db.stu.Count(),rows=data};
return Json(rult, JsonRequestBehavior.AllowGet);
} //删除的方法
[HttpPost]
public ActionResult Del(string id)
{
int ids = int.Parse(id);
try
{
var stu1 = _db.stu.Where(a => a.id == ids).FirstOrDefault();
_db.stu.DeleteObject(stu1);
_db.SaveChanges();
return Content("删除成功!");
}
catch
{
return Content("删除失败!");
}
} //添加的方法
[HttpPost]
public ActionResult Add()
{
StringBuilder sb = new StringBuilder();
//遍历获取传递过来的字符串
foreach (string s in Request.Form.AllKeys)
{
sb.AppendFormat("{0}:{1}\n", s, Request.Form[s]);
}
string ss = sb.ToString();
string[] str = ss.Split('&');
string no = str[1].Split('=')[1];
string name = str[2].Split('=')[1];
string pwd = str[3].Split('=')[1];
string sex = str[4].Split('=')[1] == "1" ? "男" : "女";
int age = int.Parse(str[5].Split('=')[1]);
string address = str[6].Split('=')[1];
try
{
var stu1 = new stu() { NO = no, NAME = name, pwd = pwd, sex = sex, age = age, ADDRESS = address };
_db.stu.AddObject(stu1);
_db.SaveChanges();
return Content("添加成功!");
}
catch
{
return Content("添加失败!");
}
} //修改的方法
[HttpPost]
public ActionResult Edit()
{
StringBuilder sb = new StringBuilder();
//遍历获取传递过来的字符串
foreach (string s in Request.Form.AllKeys)
{
sb.AppendFormat("{0}:{1}\n", s, Request.Form[s]);
}
string ss = sb.ToString();
string[] str = ss.Split('&');
int id = int.Parse(str[0].Split('=')[1]);
string no = str[1].Split('=')[1];
string name = str[2].Split('=')[1];
string pwd = str[3].Split('=')[1];
string sex = str[4].Split('=')[1] == "1" ? "男" : "女";
int age = int.Parse(str[5].Split('=')[1]);
string address = str[6].Split('=')[1];
try
{
//获取对象
stu stu1 = new stu() { id = id,NO = no, NAME = name, pwd = pwd, sex = sex, age = age, ADDRESS = address };
//添加到当前上下文中
_db.stu.Attach(stu1);
//修改状态(进行修改)
_db.ObjectStateManager.ChangeObjectState(stu1, EntityState.Modified);
_db.SaveChanges();
return Content("修改成功!");
}
catch
{
return Content("修改失败!");
}
}
}
no pains, no gains