1.进入easyui官网下载源码
2. 将上述源码中需要的jquery 有选择的加到项目中来
添加Content文件夹,放入easyui代码
1. 通过nugut 引入EF
2. 添加实体
public class Student
{
public int Id { get; set; }
/// <summary>
/// 学号
/// </summary>
public int StuNo { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 密码
/// </summary>
public string Pwd { get; set; }
/// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
/// <summary>
/// 出生日期
/// </summary>
public DateTime? BrithDate { get; set; }
/// <summary>
/// 家庭地址
/// </summary>
public string Address { get; set; }
}
3.创建dbcontext
public class EFDbContext : DbContext
{
public EFDbContext() : base("name=DbConn")
{
Database.SetInitializer<EFDbContext>(new DropCreateDatabaseIfModelChanges<EFDbContext>());
}
public DbSet<Student> Student { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().HasIndex(s=>s.StuNo).IsUnique();//添加唯一性约束
modelBuilder.Entity<Student>().Property(s=>s.Name).HasMaxLength(32).IsUnicode();//
modelBuilder.Entity<Student>().Property(s => s.Address).HasMaxLength(100).IsUnicode();
modelBuilder.Entity<Student>().Property(s => s.Sex).HasMaxLength(1).IsUnicode();
modelBuilder.Entity<Student>().Property(s => s.Pwd).HasMaxLength(80);//
}
}
4. 在webconfig中添加链接字符串
<connectionStrings>
<add name="DbConn" connectionString="Data Source=localhost;Initial Catalog=StudentDemo;User ID=test;Password=123456" providerName="System.Data.SqlClient" />
</connectionStrings>
创建StudentController、 及Index视图, 在Index上按F5运行
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
DataInit();
}
public ActionResult Login()
{
return View();
}
private void DataInit()
{
for (int i = 1; i <= 30; i++)
{
Student student = new Student();
student.Name = "张三" + i;
student.Pwd = "123456";
student.Sex = "男";
student.StuNo = i;
student.BrithDate = DateTime.Now;
student.Address = "武汉江夏";
EFDbContext dbContext = new EFDbContext();
dbContext.Student.Add(student);
dbContext.SaveChanges();
}
}
}
根据easyui官方文档说明,编写index 布局页面
@Model
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Content/EasyUI-1.7.0/jquery.min.js"></script>
<script src="~/Content/EasyUI-1.7.0/jquery.easyui.min.js"></script>
<script src="~/Content/EasyUI-1.7.0/easyui-lang-zh_CN.js"></script>
<link href="~/Content/EasyUI-1.7.0/themes/default/easyui.css" rel="stylesheet" />
<link href="~/Content/EasyUI-1.7.0/themes/icon.css" rel="stylesheet" />
<script type="text/javascript">
$(function () {
//tabs的点击事件
bindTabsEvent();
});
function bindTabsEvent() {
$(".detail").click(function () {
//拿到点击标题
var title = $(this).text();
//拿到点击的url
var url = $(this).attr("url");
//判断标签是否存在
var isExt = $("#tt").tabs("exists", title);
//如果存在则选中
if (isExt) {
$("#tt").tabs("select", title); //选中
return;
}
//不存在就添加标签
$("#tt").tabs("add", {
title: title,
content: createTabContent(url),
closable:true
});
});
}
function createTabContent(url) {
return '<iframe src="' + url + '" scrolling="no" frameborder="0" width="100%" height="100%"></iframe>';
}
</script>
</head>
<body class="easyui-layout">
<div data-options="region:'north',split:true" style="height: 50px;">
<table style="padding: 5px" width="100%">
<tr>
<td valign="bottom" align="left" width="50%">
<font size="4"> 学生演示系统
</td>
<td valign="bottom" align="right" width="50%">
<font size="3"> <strong>欢迎:</strong>@Model.Name</font> <a href="~/Student/LogOut">登出</a>
</td>
</tr>
</table>
</div>
<div data-options="region:'west',split:true,title:'West'" style="width:150px;padding:0px;">
<div class="easyui-accordion" style="width:auto;height:auto;">
<div title="学生管理" data-options="iconCls:'icon-ok'" style="overflow:auto;padding:10px;">
<a href="javascript:void(0)" class="detail" url="/Student/StudentTab">学生管理</a>
</div>
@*<div title="评论管理" data-options="iconCls:'icon-ok'" style="overflow:auto;padding:10px;">
<a href="javascript:void(0)" class="detail" url="/Student/Login">学生登录</a>
</div>*@
</div>
</div>
@*<div data-options="region:'east',split:true,collapsed:true,title:'East'" style="width:100px;padding:10px;">east region</div>*@
<div data-options="region:'south',border:false" style="height:50px;background:#A9FACD;padding:10px;">south region</div>
<div data-options="region:'center',title:'Center'">
<div class="easyui-tabs" style="width:700px;height:250px" fit="true" id="tt">
<div title="欢迎使用">
<h1 style="font-size: 24px;">欢迎!</h1>
<h1 style="font-size: 24px; color:red;"> Welcome !</h1>
</div>
</div>
</div>
</body>
</html>
后台
// GET: Student
public ActionResult Index()
{
// DataInit();
int userId;
if( Session["userId"]==null || !int.TryParse(Session["userId"].ToString(),out userId))
{
return Redirect("~/Student/Login");
}
EFDbContext dbContext = new EFDbContext();
var user = dbContext.Student.Find(userId);
return View(user);
}
private void DataInit()
{
for (int i = 1; i <= 30; i++)
{
Student student = new Student();
student.Name = "张三" + i;
student.Pwd = "123456";
student.Sex = "男";
student.StuNo = i;
student.BrithDate = DateTime.Now;
student.Address = "武汉江夏";
EFDbContext dbContext = new EFDbContext();
dbContext.Student.Add(student);
dbContext.SaveChanges();
}
}
public ActionResult StudentTab()
{
return View();
}
public JsonResult StudentList()
{
//要求返回的数据json对象 {total:200,rows:[{},{}]}
int pageSize = int.Parse(Request["rows"] ?? "10");
int pageIndex = int.Parse(Request["page"] ?? "1");
EFDbContext dbContext = new EFDbContext();
//分页数据
List<Student> studentList= dbContext.Student.OrderBy(s=>s.Id).Skip(pageSize*(pageIndex-1)).Take(pageSize).ToList();
//总共多少数据
var allCount = dbContext.Student.Count();
//把totle和rows:[{},{}]一起返回
//先建立一个匿名类
var dataJson = new { total = allCount, rows = studentList };
var json = Json(dataJson, JsonRequestBehavior.AllowGet);
return json;
}
public ActionResult AddStudent(Student data)
{
EFDbContext dbContext = new EFDbContext();
if (dbContext.Student.Where(m => m.StuNo == data.StuNo).FirstOrDefault() != null)
{
return Content("error:学号已存在,请修改后再操作!");
}
dbContext.Student.Add(data);
dbContext.SaveChanges();
return Content("ok:新增成功");
}
public ActionResult UpdateStudent(Student data)
{
EFDbContext dbContext = new EFDbContext();
var s = dbContext.Student.Find(data.Id);
if (data.StuNo != s.StuNo && dbContext.Student.Where(m=>m.StuNo==data.StuNo).FirstOrDefault()!=null)
{
return Content("error:学号已存在,请修改后再操作!");
}
s.Name = data.Name;
s.Pwd = data.Pwd;
s.Sex = data.Sex;
s.StuNo = data.StuNo;
s.BrithDate = data.BrithDate;
dbContext.SaveChanges();
return Content("ok:修改成功");
}
public ActionResult DeleteStudent(int id)
{
EFDbContext dbContext = new EFDbContext();
var s = dbContext.Student.Find(id);
dbContext.Student.Remove(s);
dbContext.SaveChanges();
return Content("ok:删除成功");
}
}
前端
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>StudentList</title>
<script src="~/Content/EasyUI-1.7.0/jquery.min.js"></script>
<script src="~/Content/EasyUI-1.7.0/jquery.easyui.min.js"></script>
<script src="~/Content/EasyUI-1.7.0/easyui-lang-zh_CN.js"></script>
<link href="~/Content/EasyUI-1.7.0/themes/default/easyui.css" rel="stylesheet" />
<link href="~/Content/EasyUI-1.7.0/themes/icon.css" rel="stylesheet" />
<script type="text/javascript">
$(function () {
//初始化表格
initTable();
//设置详细框为不可见
$("#detailDiv").css("display", "none");
//设置添加编辑框为不可见
$("#addDiv").css("display","none");
//设置输入框为禁用
// $("#Id").textbox('textbox').attr('readonly', true);
// $("#Name").textbox('textbox').attr('readonly', true);
// $("#BrithDate").textbox('textbox').attr('readonly', true);
});
//初始化表格
function initTable() {
$("#tt").datagrid({
//指向一个地址,当表格加载完成后自动请求该地址
//自动向后台发送 rows 当前页多少条数据 page:当前页
//要求返回的数据json对象 {total:200,rows:[{},{}]}
url: '/Student/StudentList',
title: "学生管理",
fitColumns: true,
height: $(window).height()-10,
idField: 'Id', //后台返回数据中的主键列。一定注意大小写。
loadMsg: "正在加载学生信息........",
pagination: true, //启用分页
singleSelect: true, //只允许选中一行
pageSize: 10, //一页默认多少条
pageNumber: 1, //默认页
rownumbers: true,//行号
pageList: [10, 20, 30], //允许一页多少条数据
queryParams: {}, //异步请求可以额外传递的数据
columns: [[
{ field: 'ck', checkbox: true, align: 'left', width: 10 }, // 设置cheakbox formatter: ChangeDateFormat
{ field: 'Id', title: '序号', width: 20 },
{ field: 'StuNo', title: '学号', width: 20 },
{ field: 'Name', title: '姓名', width: 20 },
{ field: 'Pwd', title: '密码', width: 20 },
{ field: 'Sex', title: '性别', width: 20 },
{ field: 'BrithDate', title: '出生日期', width: 30, formatter: ChangeDateFormat },
{ field: 'Address', title: '家庭地址', width: 20 },
{
field: 'operate', title: '操作', align: 'center', width: 30,
formatter: function (value, row, index) {
var str = "";
str += '<a href="#" name="update" id="update" class="easyui-linkbutton" onclick="updateStudent(' + row.Id + ')" ></a>';
str += ' ',
str += '<a href="#" name="delete" id="delete" class="easyui-linkbutton" onclick="deleteStudent(' + row.Id + ')" ></a>';
return str;
}
}
]],
onLoadSuccess: function (data) {
$("a[name='update']").linkbutton({ text: '编辑', plain: true, iconCls: 'icon-edit' });
$("a[name='delete']").linkbutton({ text: '删除', plain: true, iconCls: 'icon-cancel' });
},
toolbar: [{
id: 'btnAdd',
text: '添加',
iconCls: 'icon-add',
handler: function () {
addBtnClick(); //添加学生
}
}],
});
}
function ChangeDateFormat(cellval) {
var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear() + "-" + month + "-" + currentDate;
}
function ChangeDateFormat2(cellval) {
var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return month + "/" + currentDate + "/" + date.getFullYear();
}
//添加学生确定按钮
function addBtnClick() {
$("#addDiv").css("display", "block");
$("#id_show_not").css("display", "none");
$("#addDiv").dialog({
title: "添加学生",
modal: true,
width: 350,
height: 320,
open:function(){
},
buttons: [{
text: "确定",
iconCls: "icon-ok",
handler: function () {
if ($("#stuNo").val().length == 0) {
$.messager.alert("字段提示", "学号不能为空", "info");
return;
}
if ($("#name").val().length == 0) {
$.messager.alert("字段提示", "姓名不能为空", "info");
return;
}
if ($("#pwd").val().length == 0) {
$.messager.alert("字段提示", "密码不能为空", "info");
return;
}
if ($("#brithDate").val().length == 0) {
$.messager.alert("字段提示", "出生日期不能为空", "info");
return;
}
var postData = {
stuNO : $("#stuNo").val(),
name : $("#name").val(),
pwd :$("#pwd").val(),
sex: $('input[name="sex"]:checked').val(),
brithDate:$("#brithDate").val(),
address: $("#address").val()
}
$.post("/Student/AddStudent", { data: postData }, function (data) {
var serverData = data.split(':');
if (serverData[0] == "ok") {
$.messager.alert("提示", "新增成功", "info");
$("#addDiv").dialog("close"); //关闭窗口
$('#tt').datagrid('reload'); //刷新单表
}
else if (serverData[0] == "error") {
$.messager.alert("提示", serverData[1], "info");
$("#addDiv").dialog("close"); //关闭窗口
$('#tt').datagrid('reload'); //刷新单表
}
else {
$.messager.alert("提示", "新增失败", "info");
$("#addDiv").dialog("close"); //关闭窗口
$('#tt').datagrid('reload'); //刷新单表
}
});
}
}, {
text: "取消",
iconCls: "icon-cancel",
handler: function () {
$("#addDiv").dialog("close");
}
}]
});
}
//修改学生确定按钮
function updateStudent(index) {
var row = $('#tt').datagrid('getSelected');
$("#id").textbox("setValue", row.Id);
$("#stuNo").textbox("setValue", row.StuNo);
$("#name").textbox("setValue", row.Name);
$("#pwd").textbox("setValue", row.Pwd);
$(":radio[name='sex'][value='" + row.Sex + "']").prop("checked", "checked");
$("#brithDate").datebox("setValue", ChangeDateFormat2(row.BrithDate));
$("#address").textbox("setValue", row.Address);
var a= $("#id").val();
$("#addDiv").css("display", "block");
$("#id_show_not").css("display", "none");
$("#addDiv").dialog({
title: "修改学生",
modal: true,
width: 350,
height: 320,
open: function () {
},
buttons: [{
text: "确定",
iconCls: "icon-ok",
handler: function () {
if ($("#stuNo").val().length == 0) {
$.messager.alert("字段提示", "学号不能为空", "info");
return;
}
if ($("#name").val().length == 0) {
$.messager.alert("字段提示", "姓名不能为空", "info");
return;
}
if ($("#pwd").val().length == 0) {
$.messager.alert("字段提示", "密码不能为空", "info");
return;
}
if ($("#brithDate").val().length == 0) {
$.messager.alert("字段提示", "出生日期不能为空", "info");
return;
}
var postData = {
id:$("#id").val(),
stuNO: $("#stuNo").val(),
name: $("#name").val(),
pwd: $("#pwd").val(),
sex: $('input[name="sex"]:checked').val(),
brithDate: $("#brithDate").val(),
address: $("#address").val()
}
$.post("/Student/UpdateStudent", { data: postData }, function (dataaa) {
var serverData = dataaa.split(':');
if (serverData[0] == "ok") {
$.messager.alert("提示", "修改成功", "info");
$("#addDiv").dialog("close"); //关闭窗口
$('#tt').datagrid('reload'); //刷新单表
}
else if (serverData[0] == "error") {
$.messager.alert("提示", serverData[1], "info");
$("#addDiv").dialog("close"); //关闭窗口
$('#tt').datagrid('reload'); //刷新单表
}
else {
$.messager.alert("提示", "修改失败", "info");
$("#addDiv").dialog("close"); //关闭窗口
$('#tt').datagrid('reload'); //刷新单表
}
});
}
}, {
text: "取消",
iconCls: "icon-cancel",
handler: function () {
$("#addDiv").dialog("close");
}
}]
});
}
//删除学生
function deleteStudent(index) {
$.messager.confirm("提示", "确定要删除吗?", function (r) {
if (r) {
$.post("/Student/DeleteStudent", { id: index }, function (data) {
if (data.substring(0, 2) == "ok") {
//刷新表格
$('#tt').datagrid('reload');
$.messager.alert("提示", "删除成功", "info");
}
else {
$.messager.alert("提示","删除失败","info");
}
});
}
});
}
</script>
</head>
<body>
<div>
<table id="tt"></table>
</div>
<!---------------------添加和编辑域开始-------------------------->
<div id="addDiv">
<form id="addForm">
<table>
<tr id="id_show_not">
<td>Id:</td>
<td><input class="easyui-textbox" style="width:250px;height:32px" id="id" name="id" /></td>
</tr>
<tr>
<td>学号:</td>
<td><input class="easyui-textbox" style="width: 250px; height: 32px" id="stuNo" name="stuNo" /></td>
</tr>
<tr>
<td>姓名:</td>
<td><input class="easyui-textbox" style="width: 250px; height: 32px" id="name" name="name" /></td>
</tr>
<tr>
<td>密码:</td>
<td><input class="easyui-textbox" style="width: 250px; height: 32px" id="pwd" name="pwd" /></td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" class="sex" name="sex" value="男" checked="checked" />男
<input type="radio" class="sex" name="sex" value="女" />女
</td>
</tr>
<tr>
<td>出生日期:</td>
<td><input class="easyui-datebox " style=" width:250px; height :32px ;" id="brithDate" name="brithDate" data-option="required:true,showSeconds:false" /></td>
</tr>
<tr>
<td>家庭地址:</td>
<td><input class="easyui-textbox" style="width: 250px; height: 32px" id="address" name="address" /></td>
</tr>
</table>
</form>
</div>
<!---------------------添加和编辑域结束-------------------------->
</body>
</html>
后端
public ActionResult Login()
{
return View();
}
/// <summary>
/// 生成验证码
/// </summary>
/// <returns></returns>
public ActionResult ValidateCode()
{
ValidateCode validateCode = new ValidateCode();
string code = validateCode.CreateValidateCode(4);//生成的验证码4个长度
Session["validateCode"] = code;
byte[] buffer = validateCode.CreateValidateGraphic(code);//创建验证码图片
return File(buffer, "image/jpeg");//返回图片
}
public ActionResult CheckLogin()
{
//拿到session的值
string Vcode = Session["validateCode"].ToString();
string requestCode = Request["txtVcode"].ToString();
string userName = Request["txtName"].ToString();
string userPwd = Request["txtPwd"].ToString();
if (!requestCode.Equals(Vcode, StringComparison.CurrentCultureIgnoreCase))
{
return Content("no:验证码错误!!");
}
EFDbContext dbContext = new EFDbContext();
var student = dbContext.Student.Where(s => s.Name == userName && s.Pwd == userPwd).FirstOrDefault();
if (student!= null)
{
//清空validateCode
Session["validateCode"] = null;
Session["userId"] = student.Id;
return Content("ok:登录成功");
}
else
{
return Content("no:用户名或者密码错误");
}
}
public ActionResult LogOut()
{
Session["userId"] = null;
return Redirect("~/Student/Login");
}
}
前台
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>登录</title>
<script src="~/Content/EasyUI-1.7.0/jquery.min.js"></script>
<script src="~/Content/EasyUI-1.7.0/jquery.easyui.min.js"></script>
<script src="~/Content/EasyUI-1.7.0/easyui-lang-zh_CN.js"></script>
<link href="~/Content/EasyUI-1.7.0/themes/default/easyui.css" rel="stylesheet" />
<link href="~/Content/EasyUI-1.7.0/themes/icon.css" rel="stylesheet" />
<script type="text/javascript">
$(function () {
initWin(); //初始化登录窗体
changeCheckCode(); //切换验证码
cheakLogin(); //验证登录
});
//验证登录
function cheakLogin() {
$("#btnOk").click(function () {
if ($("#txtName").val() == "") {
$("#spanName").text("必填");
}
else {
$("#spanName").text("");
}
if ($("#txtPwd").val() == "") {
$("#spanPwd").text("必填");
}
else {
$("#spanPwd").text("");
}
if ($("#txtVcode").val() == "") {
$("#spanVcode").text("必填");
}
else {
$("#spanVcode").text("");
}
if ($("#txtName").val() != "" && $("#txtPwd").val() != "" && $("#txtVcode").val() != "") {
//先把表单序列化为json对象
var jsonForm = $("#loginForm").serializeArray();
//把数据异步提交到后台
$.ajax({
type: "post",
url: "/Student/CheckLogin",
data: jsonForm,
success: function (data) {
var serverData = data.split(':');
if (serverData[0] == "ok") {
window.location.href = "/Student/Index";
}
else if (serverData[0] == "no") {
$("#spanCheak").text(serverData[1]);
}
else {
$("#spanCheak").text("异常错误");
}
}
});
}
});
}
//初始化登录窗体
function initWin() {
$("#win").window({
title: "登录",
width: 400,
height: 300,
collapsible: false,
minimizable: false,
maximizable: false,
closable: false,
modal: true,
resizable: false,
});
}
//切换验证码
function changeCheckCode() {
$("#changeVcode").click(function () {
$("#image").attr("src", $("#image").attr("src") + 1);
});
}
</script>
</head>
<body>
<div id="win" class="easyui-window">
<div>
<div style="height:20px"></div>
<form id="loginForm">
<table>
<tr>
<td style="width:20px"></td>
<td>用户名:</td>
<td><input type="text" class="easyui-textbox" id="txtName" name="txtName" /></td>
<td><span id="spanName" style="color:red"></span></td>
</tr>
<tr style="height:10px"></tr>
<tr>
<td style="width:20px"></td>
<td>密 码:</td>
<td><input type="password" class="easyui-textbox" id="txtPwd" name="txtPwd"></td>
<td><span id="spanPwd" style="color:red"></span></td>
</tr>
<tr style="height:10px"></tr>
<tr>
<td style="width:20px"></td>
<td>验证码:</td>
<td><input type="text" class="easyui-textbox" id="txtVcode" name="txtVcode" /></td>
<td><span id="spanVcode" style="color:red"></span></td>
</tr>
<tr style="height:10px"></tr>
<tr>
<td style="width:20px"></td>
<td><img id="image" src="/Student/ValidateCode/?id=1" style="float: left; height: 24px;" /></td>
<td><a href="javascript:void(0)" id="changeVcode">看不清,换一张</a></td>
</tr>
</table>
</form>
</div>
<div style="height:10px"></div>
<div data-options="region:'south',border:false" style="text-align:center;padding:5px 0 0;">
<a class="easyui-linkbutton" data-options="iconCls:'icon-ok'" href="javascript:void(0)" id="btnOk" style="width:80px">登录</a>
<span id="spanCheak" style="color:red"></span>
</div>
</body>
</html>
有兴趣研究的。可以进QQ群,在群在线文档里面进行下载。