分享Entity Framework4.1+MVC3+Jquery EasyUI的DEMO
花了一下午手写了这个Demo,差不多注释下,通俗易懂的Entity Framework4.1+MVC3+Jquery EasyUI的后台管理系统,现分享如下,
关于Entity Framework4.1+MVC3的基础可以看
http://www.cnblogs.com/wlflovenet/archive/2011/07/24/EFandMvc2.html
关于Jquery EasyUI的API文档可以看
http://www.phptogether.com/juidoc/ 中文API说明
http://www.jeasyui.com/demo/index.php 英文说明及其DEMO 分js和html布局
http://www.bhcode.net/article/20120327/22427.html jquery easyui datagrid 分页使用详解
主要代码如下:
视图部分:
@{ ViewBag.Title = "产品信息"; } @section Head{ <script src="@Url.Content("~/Scripts/Product.js")" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#TypeId,#TypeId2").combobox({ url: "/Admin/GetTypesList", editable: false, valueField: "ID", textField: "ProductTypeName", panelHeight: "auto" }); }); </script> } <div region="center" style="width: 550px; height: 300px; padding: 1px;overflow-y: hidden"> <div id="grid" > </div> </div> <div id="Dlg-Edit" title="窗口" style="width: 500px; height: 300px;" buttons="#buttons"> <div style="padding: 20px 20px 40px 40px;"> <form method="post" id="Form1"> <table> <tr> <td style="text-align:right"> 产品类型: </td> <td> <select id="TypeId" class="easyui-combogrid" name="ProductTypeID" style="width:200px;" class="easyui-validatebox" required="true"> </select> </td> </tr> <tr> <td style="text-align:right"> 产品名称: </td> <td> <input type="text" name="ProductName" id="ProductName" class="easyui-validatebox" required="true" style="width: 200px;" maxlength=25 /> (限制:50个字节) </td> </tr> <tr> <td style="text-align:right"> 产品图片: </td> <td> <input type="text" name="Image" id="Image" class="easyui-validatebox" required="true" style="width: 200px;" /> </td> </tr> <tr> <td style="text-align:right"> 市场价格: </td> <td> <input type="text" name="MarketPrice" id="MarketPrice" class="easyui-validatebox" required="true" onkeyup="value=value.replace(/[^\d]/g,'')" style="width: 200px;" /> (单位:元)</td> </tr> <tr> <td style="text-align:right"> 本店价格: </td> <td> <input name="NewPrice" id="NewPrice" class="easyui-validatebox" required="true" style="width: 200px;" onkeyup="value=value.replace(/[^\d]/g,'')" /> (单位:元)</td> </tr> <tr> <td style="text-align:right"> 是否上架: </td> <td> <select id="Enable" class="easyui-combobox" name="Enable" style="width:200px;" class="easyui-validatebox" required="true" editable="false" panelHeight= "auto"> <option value="1">上架</option> @*true在网页中格式化了1*@ <option value="0">下架</option> </select> (默认:上架) </td> </tr> </table> </form> </div> </div> <div id="buttons"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveData()">保存</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#Dlg-Edit').dialog('close')">关闭</a> </div> <div id="search-window" title="搜索产品信息" style="width: 350px; height: 250px;padding:10px" > <div style="padding:10px;background:#fff;border:1px solid #ccc;"> <form method="post" id="Form2"> <table> <tr> <td style="text-align:right"> 产品类型: </td> <td> <select id="TypeId2" class="easyui-combobox" name="TypeId2" style="width:150px;" > </select> </td> </tr> <tr> <td style="text-align:right"> 产品编号: </td> <td> <input name="pid" id="pid" style="width: 150px;" onkeyup="value=value.replace(/[^\d]/g,'')"/> </td> </tr> <tr> <td style="text-align:right"> 产品名称: </td> <td> <input id="Name" class="easyui-combogrid" name="Name" style="width:150px;" /> </td> </tr> <tr> <td style="text-align:right"> 本店价格: </td> <td> <input name="Price" id="Price" style="width: 150px;" onkeyup="value=value.replace(/[^\d]/g,'')"/> </td> </tr> <tr> <td style="text-align:right"> 是否上架: </td> <td> <select id="Enable2" class="easyui-combobox" name="Enable2" style="width:150px;" class="easyui-validatebox" required="true" editable="false" panelHeight= "auto"> <option value="">不选</option> <option value="1">上架</option> @*true在网页中格式化了1*@ <option value="0">下架</option> </select> </td> </tr> </table> </form> </div> <div style="text-align: right; padding: 5px;vertical-align:bottom"> <a href="javascript:void(0)" onclick="SearchOK()" id="btn-search" icon="icon-ok">搜索</a> <a href="javascript:void(0)" onclick="closeSearchWindow()" id="btn-search-cancel" icon="icon-cancel"> 取消</a> </div> </div>
Js部分:
// 全局变量 var grid; var dlg_Edit; var dlg_Edit_form; var searchWin; var searchForm; var virpath = ""; //网站的虚拟目录 如:/ShopManager $(function () { grid = $('#grid').datagrid({ title: '产品管理', iconCls: 'icon-save', methord: 'post', url: '/Admin/LoadProductjson/', sortName: 'ID', sortOrder: 'desc', idField: 'ID', pageSize: 20, striped: true, //奇偶行是否区分 frozenColumns: [[ { field: 'ck', checkbox: true } ]], columns: [[ { field: 'ID', title: '编号', width: 50, sortable: true, rowspan: 2 }, { field: 'Image', title: '产品图片', width: 60, rowspan: 2, align: 'center', formatter: function (value, row, index) { return "<img src='" + row.Image + "' alt='" + row.ProductName + "' width='60px',higth='60px' />"; } }, { field: 'ProductTypeName', title: '所属类型', width: 100, sortable: true, rowspan: 2 }, { field: 'ProductName', title: '产品名称', width: 150, sortable: true, rowspan: 2 }, { title: '价格(单位:元)', colspan: 2 }, { field: 'GetDate', title: '录入/修改时间', width: 120, sortable: true,align: 'center', rowspan: 2 }, { field: 'Enable', title: '状态', width: 50, rowspan: 2, formatter: function (value, row, index) { if (row.Enable) { return "出售中"; } else { return "已下架"; } }, styler: function (value, row, index) { if (!row.Enabled) { return 'background-color:#ffee00;color:red;'; } } } ], [{ field: 'MarketPrice', title: '市场价', width: 80, sortable: true }, { field: 'NewPrice', title: '真实价', width: 80, sortable: true}] ], // onLoadSuccess: function () { // var merges = [{ // index: 2, // rowspan: 2 // }, { // index: 5, // rowspan: 2 // }, { // index: 7, // rowspan: 2 // }]; // for (var i = 0; i < merges.length; i++) // $('#grid').datagrid('mergeCells', { // index: merges[i].index, // field: 'GameName', // rowspan: merges[i].rowspan // }); // }, fit: true, pagination: true, rownumbers: true, fitColumns: true, singleSelect: false, toolbar: [{ text: '新增', iconCls: 'icon-add', handler: add }, '-', { text: '修改', iconCls: 'icon-edit', handler: edit }, '-', { text: '删除', iconCls: 'icon-remove', handler: del }, '-', { text: '高级搜索', iconCls: 'icon-search', handler: OpensearchWin }, '-', { text: '所有', iconCls: 'icon-search', handler: showAll }], onDblClickRow: function (rowIndex, rowData) { //双击事件 dlg_Edit.dialog('open'); dlg_Edit_form.form('clear'); //清除之前面选中的表单 dlg_Edit.dialog('setTitle', '您正在查看的是:' + rowData.ProductTypeName + "->" + rowData.ProductName ); dlg_Edit_form.form('load', rowData); //加载到表单的控件上 dlg_Edit_form.url = virpath + '/Admin/UpdateProduct?id=' + rowData.ID; }, onHeaderContextMenu: function (e, field) { e.preventDefault(); if (!$('#tmenu').length) { createColumnMenu(); } $('#tmenu').menu('show', { left: e.pageX, top: e.pageY }); } }); dlg_Edit = $('#Dlg-Edit').dialog({ closed: true, modal: true, toolbar: [{ text: '保存', iconCls: 'icon-save', handler: saveData }, '-', { text: '关闭', iconCls: 'icon-no', handler: function () { dlg_Edit.dialog('close'); } }] }); dlg_Edit_form = dlg_Edit.find('form'); $('#btn-search,#btn-search-cancel').linkbutton(); searchWin = $('#search-window').window({ iconCls: 'icon-search', closed: true, modal: true }); searchForm = searchWin.find('form'); $('body').layout(); }); function createColumnMenu() { var tmenu = $('<div id="tmenu" style="width:100px;"></div>').appendTo('body'); var fields = grid.datagrid('getColumnFields'); for (var i = 0; i < fields.length; i++) { $('<div iconCls="icon-ok"/>').html(fields[i]).appendTo(tmenu); } tmenu.menu({ onClick: function (item) { if (item.iconCls == 'icon-ok') { grid.datagrid('hideColumn', item.text); tmenu.menu('setIcon', { target: item.target, iconCls: 'icon-empty' }); } else { grid.datagrid('showColumn', item.text); tmenu.menu('setIcon', { target: item.target, iconCls: 'icon-ok' }); } } }); } function getSelectedArr() { var ids = []; var rows = grid.datagrid('getSelections'); for (var i = 0; i < rows.length; i++) { ids.push(rows[i].ID); } return ids; } function getSelectedID() { var ids = getSelectedArr(); return ids.join(','); } function arr2str(arr) { return arr.join(','); } function add() { dlg_Edit_form.form('clear'); dlg_Edit.dialog('open'); dlg_Edit.dialog('setTitle', '添加产品信息'); //$("#ProductId2").removeAttr("readonly"); //移除只读 $('#Enable').combobox('setValue', true); //默认设置开启 dlg_Edit_form.url = virpath + '/Admin/CreateProduct/'; Msgalert("提示", '成功调用', "info"); } function edit() { var rows = grid.datagrid('getSelections'); var num = rows.length; if (num == 0) { Msgshow('请选择一条记录进行操作!'); return; } else if (num > 1) { Msgfade('您选择了多条记录,只能选择一条记录进行修改!'); //$.messager.alert('提示', '您选择了多条记录,只能选择一条记录进行修改!', 'info'); return; } else { //alert(rows[0].ProductId); dlg_Edit_form.form('clear'); dlg_Edit.dialog('open'); dlg_Edit.dialog('setTitle', '您正在修改的是:' + rows[0].ProductTypeName + "->" + rows[0].ProductName ); dlg_Edit_form.form('load', rows[0]); //加载到表单的控件上 // $("#tishi").html("禁止修改"); dlg_Edit_form.url = virpath + '/Admin/UpdateProduct?id=' + rows[0].ID; } } function del() { var arr = getSelectedArr(); alert(arr); if (arr.length > 0) { $.messager.confirm('提示信息', '您确认要删除选中的记录吗?', function (data) { if (data) { $.ajax({ url: virpath + '/Admin/RemeProducts?ids=' + arr2str(arr), type: 'post', error: function () { Msgalert('错误', '删除失败!', 'error'); grid.datagrid('clearSelections'); }, success: function (re) { var data = eval('(' + re + ')'); if (data.success) { Msgfade(arr.length + "条记录" + data.msg); //提示消息 grid.datagrid('reload'); grid.datagrid('clearSelections'); //清除所有选中的元素 } else { Msgalert('错误', data.msg, 'error'); } } }); } }); } else { Msgshow('请先选择要删除的记录。'); } } function saveData() { //alert(dlg_Edit_form.url); dlg_Edit_form.form('submit', { url: dlg_Edit_form.url, onSubmit: function () { return $(this).form('validate'); }, success: successCallback }); } function showAll() { grid.datagrid({ url: virpath + '/Admin/LoadProductjson/' }); } function OpensearchWin() { searchWin.window('open'); searchForm.form('clear'); $('#Enable2').combobox('setValue', true); //默认设置开启搜素 } function SearchOK() { var Name = $("#Name").val(); var Id = $("#TypeId2").combobox("getValue"); var bl = $('#Enable2').combobox('getValue'); //默认设置开启搜素 var PId = $("#pid").val(); //ID var Price = $("#Price").val(); //价格 // alert(Name + "==" + Id + "==" + MId + "==" + bl + "==" + CId+"=="+Code); searchWin.window('close'); grid.datagrid({ url: virpath + '/Admin/SeachProductInfo/', queryParams: { ProductName: Name, typeId: Id, ProductId: PId, RealPrice: Price, en: bl} }); //经过测试queryParams参数可以提交到后台通过FormCollection获取 也可以Request["ProductName"]=?获取 } function closeSearchWindow() { searchWin.window('close'); }
后台部分:
#region 产品管理 /// <summary> /// 加载json数组对象 /// </summary> /// <returns></returns> public ActionResult LoadProductjson() { //string sort = Request["sort"].ToString();ef暂时实现不了动态的字段倒/正排序 除非用Switch 但又显得很臃肿 //sort = (!string.IsNullOrEmpty(sort) ? sort : "ProductId"); //string order = Request["order"].ToString(); //order = (!string.IsNullOrEmpty(order) ? order : "ascending"); int row = int.Parse(Request["rows"].ToString()); int pageindex = int.Parse(Request["page"].ToString()); ProductData Productjson = new ProductData(); int total; Productjson.rows = productBLL.GetProductList(pageindex, row, out total); Productjson.total = total; string Str = JsonConvert.SerializeObject(Productjson); return Content(Str, "text/html;charset=UTF-8");
//return Json(Productjson, "text/html;charset=UTF-8"); //MVC3自带的jsonResult 方法也可
} /// <summary> /// 搜索 /// </summary> /// <param name="collection"></param> /// <returns></returns> public ActionResult SeachProductInfo(FormCollection collection) { String Name = collection.Get("ProductName").Trim().ToString(); //判断空值 String Id = collection.Get("typeId").ToString(); int typeId = Convert.ToInt32(String.IsNullOrEmpty(Id) ? "0" : Id); //$("#typeId").combobox("getValue"); 通过这个获取的 String sid = collection.Get("ProductId").ToString(); int ProductId = Convert.ToInt32(String.IsNullOrEmpty(sid) ? "0" : sid); String NewPrice = collection.Get("RealPrice").ToString(); int RealPrice = Convert.ToInt32(String.IsNullOrEmpty(NewPrice) ? "0" : NewPrice); String en = collection.Get("en").ToString(); bool? enable = String.IsNullOrEmpty(en) ? null : AdminController.Enable(en); //上下两种方法都可以获取数据Request[""]和collection.Get("") int row = int.Parse(Request["rows"].ToString()); int pageindex = int.Parse(Request["page"].ToString()); ProductData Productjson = new ProductData(); int total; Productjson.rows = productBLL.GetProductsBySerach(pageindex, row, out total, typeId, ProductId, Name, RealPrice, enable); Productjson.total = total; string Str = JsonConvert.SerializeObject(Productjson); return Content(Str, "text/html;charset=UTF-8"); } /// <summary> /// 增加 /// </summary> /// <param name="collection"></param> /// <returns></returns> public ActionResult CreateProduct(FormCollection collection) { Product info = new Product(); info.ProductTypeID = Convert.ToInt32(collection.Get("ProductTypeID")); string name=(!string.IsNullOrEmpty(collection.Get("ProductName"))? collection.Get("ProductName") : null); info.ProductName = name; info.Image = collection.Get("Image"); info.MarketPrice = Convert.ToInt32(collection.Get("MarketPrice")); info.NewPrice = Convert.ToInt32(collection.Get("NewPrice")); string en = collection.Get("Enable").ToString(); info.Enable = AdminController.Enable(en); info.GetDate = DateTime.Now; Message msg; if (productBLL.GreateProduct(info)) { msg = new Message(true, "添加"+name+"信息成功!"); } else { msg = new Message(false, "失败,操作有误"); } return Content(JsonConvert.SerializeObject(msg), "text/html;charset=UTF-8"); } /// <summary> /// 删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> public ActionResult RemeProducts(string ids) { String[] id = ids.Split(','); Message msg; if (ids != null) { int i = productBLL.RemeProduct(id); if (i > 0) { msg = new Message(true, "删除成功"); } else { msg = new Message(false, "删除失败"); } } else { msg = new Message(false, "传值失败,请告诉开发者解决"); } return Content(JsonConvert.SerializeObject(msg), "text/html;charset=UTF-8"); } /// <summary> /// 更新 /// </summary> /// <param name="id"></param> /// <param name="collection"></param> /// <returns></returns> public ActionResult UpdateProduct(int id, FormCollection collection) { Product info = new Product(); info.ID = id; info.ProductTypeID = Convert.ToInt32(collection.Get("ProductTypeID")); string name = (!string.IsNullOrEmpty(collection.Get("ProductName")) ? collection.Get("ProductName") : null); info.ProductName = name; info.Image = collection.Get("Image"); info.MarketPrice = Convert.ToInt32(collection.Get("MarketPrice")); info.NewPrice = Convert.ToInt32(collection.Get("NewPrice")); string en = collection.Get("Enable").ToString(); info.Enable = AdminController.Enable(en); info.GetDate = DateTime.Now; Message msg; if (productBLL.UpdateProduct(info)) { msg = new Message(true, "修改" + name + "信息成功!"); } else { msg = new Message(false, "修改" + name + "失败!"); } return Content(JsonConvert.SerializeObject(msg), "text/html;charset=UTF-8"); } #endregion
在WebConfig文件中修改你的配置地址就可以正常运行了
<connectionStrings>
<add name="MyProject" connectionString="Data Source=.;Initial Catalog=MyPorjectBD;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient"/>
</connectionStrings>
注意: 最好在VS2010+sql2008R2(2005也行)运行 ,不要忘记了是MVC3的环境,在项目加载成功后数据库就生成了,所以不要向我要数据库!