花了一下午手寫了這個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部分:
View Code
// 全局變量 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的環境,在項目加載成功后數據庫就生成了,所以不要向我要數據庫!
