1.進入easyui官網下載源碼javascript
2. 將上述源碼中須要的jquery 有選擇的加到項目中來css
添加Content文件夾,放入easyui代碼html
1. 經過nugut 引入EF前端
2. 添加實體java
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.建立dbcontextjquery
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中添加連接字符串web
<connectionStrings> <add name="DbConn" connectionString="Data Source=localhost;Initial Catalog=StudentDemo;User ID=test;Password=123456" providerName="System.Data.SqlClient" /> </connectionStrings>
ajax
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>
後臺json
// 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>