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 分頁使用詳解
主要代碼如下:
視圖部分:
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的環境,在項目加載成功後數據庫就生成了,所以不要向我要數據庫!