第一次看到ACE模板,有種感動,有種相見恨晚的感受,因而迅速來研究。它自己是基於bootstrap和jqueryui,但更nice,整合以後爲後臺開發節省了大量時間。 發現雖然不是完美,總體效果仍是不錯,特此分享給園友。這一節先講其中的Jqgrid。按照國際慣例,先上兩張圖。javascript
集成了button,form,treeview以及日曆,時間軸、chart等控件,很是豐富。下面是Jqgrid在MVC中的使用。php
jqgrid的加載,排序,查找都是基於後臺方法,不是在內存中完成,但也有一些小坑。下面一一道來。css
1、引入ace模板html
ace自己考慮了對ie的兼容,加上bootstrap和jqueryui因此引入的樣式和腳本文件比較多。我拿掉了一下googlefont的連接,請求太慢了,你懂的。如今MVC最關心的就是RenderBody的位置。在page-content下的Row,也能夠將page-header放入子頁面中去,本身多寫幾個元素,這個就在於你本身的選擇了。 html5
<div class="page-content"> <div class="page-header"> <h1> <span>控制檯</span> <small> <i class="icon-double-angle-right"></i> <span>查看</span> </small> </h1> </div><!-- /.page-header --> <div class="row"> <div class="col-xs-12"> <!-- PAGE CONTENT BEGINS --> @RenderBody() <!-- PAGE CONTENT ENDS --> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.page-content -->
所有的layout.cshtmljava
<!DOCTYPE html> <html > <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>@ViewBag.Title</title> <link href="~/Content/CSS/bootstrap.min.css" rel="stylesheet" /> <link rel="stylesheet" href="~/Content/CSS/font-awesome.min.css" /> <script src="~/Content/Js/jquery-2.0.3.min.js"></script> <link href="~/Content/CSS/niqiu.css" rel="stylesheet" /> <!--[if IE 7]> <link rel="stylesheet" href="~/Content/CSS/font-awesome-ie7.min.css" /> <![endif]--> <!-- page specific plugin styles --> <!-- ace styles --> <link rel="stylesheet" href="~/Content/CSS/ace.min.css" /> <link rel="stylesheet" href="~/Content/CSS/ace-rtl.min.css" /> <link rel="stylesheet" href="~/Content/CSS/ace-skins.min.css" /> <!--[if lte IE 8]> <link rel="stylesheet" href="~/Content/CSS/ace-ie.min.css" /> <![endif]--> <!-- inline styles related to this page --> <!-- ace settings handler --> <script src="~/Content/Js/ace-extra.min.js"></script> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="~/Content/Js/html5shiv.js"></script> <script src="~/Content/Js/respond.min.js"></script> <![endif]--> </head> <body> <div class="navbar navbar-default" id="navbar"> <script type="text/javascript"> try { ace.settings.check('navbar', 'fixed') } catch (e) { } </script> <div class="navbar-container" id="navbar-container"> <div class="navbar-header pull-left"> <a href="#" class="navbar-brand"> <small> <i class="icon-leaf"></i> XiaoNao Admin </small> </a><!-- /.brand --> </div><!-- /.navbar-header --> <div class="navbar-header pull-right" role="navigation"> <ul class="nav ace-nav"> <li class="green"> <a data-toggle="dropdown" class="dropdown-toggle" href="#"> <i class="icon-envelope icon-animated-vertical"></i> <span class="badge badge-success">5</span> </a> <ul class="pull-right dropdown-navbar dropdown-menu dropdown-caret dropdown-close"> <li class="dropdown-header"> <i class="icon-envelope-alt"></i> 5 Messages </li> <li> <a href="#"> <img src="~/Content/avatars/avatar.png" class="msg-photo" alt="Alex's Avatar" /> <span class="msg-body"> <span class="msg-title"> <span class="blue">Alex:</span> Ciao sociis natoque penatibus et auctor ... </span> <span class="msg-time"> <i class="icon-time"></i> <span>a moment ago</span> </span> </span> </a> </li> <li> <a href="#"> <img src="~/Content/avatars/avatar3.png" class="msg-photo" alt="Susan's Avatar" /> <span class="msg-body"> <span class="msg-title"> <span class="blue">Susan:</span> Vestibulum id ligula porta felis euismod ... </span> <span class="msg-time"> <i class="icon-time"></i> <span>20 minutes ago</span> </span> </span> </a> </li> <li> <a href="#"> <img src="~/Content/avatars/avatar4.png" class="msg-photo" alt="Bob's Avatar" /> <span class="msg-body"> <span class="msg-title"> <span class="blue">Bob:</span> Nullam quis risus eget urna mollis ornare ... </span> <span class="msg-time"> <i class="icon-time"></i> <span>3:15 pm</span> </span> </span> </a> </li> <li> <a href="#"> See all messages <i class="icon-arrow-right"></i> </a> </li> </ul> </li> <li class="light-blue"> <a data-toggle="dropdown" href="#" class="dropdown-toggle"> <img class="nav-user-photo" src="~/Content/avatars/user.jpg" alt="Jason's Photo" /> <span class="user-info"> @if( Session["uname"]!=null){ <small>Welcome,</small> @Session["uname"].ToString(); } </span> <i class="icon-caret-down"></i> </a> <ul class="user-menu pull-right dropdown-menu dropdown-yellow dropdown-caret dropdown-close"> <li> <a href="#"> <i class="icon-cog"></i> Settings </a> </li> <li> <a href="#"> <i class="icon-user"></i> Profile </a> </li> <li class="divider"></li> <li> <a href="@Url.Action("LogOff","User")"> <i class="icon-off"></i> Logout </a> </li> </ul> </li> </ul><!-- /.ace-nav --> </div><!-- /.navbar-header --> </div><!-- /.container --> </div> <div class="main-container" id="main-container"> <script type="text/javascript"> try { ace.settings.check('main-container', 'fixed') } catch (e) { } </script> <div class="main-container-inner"> <a class="menu-toggler" id="menu-toggler" href="#"> <span class="menu-text"></span> </a> <div class="sidebar" id="sidebar"> <script type="text/javascript"> try { ace.settings.check('sidebar', 'fixed') } catch (e) { } </script> <div class="sidebar-shortcuts" id="sidebar-shortcuts"> <div class="sidebar-shortcuts-large" id="sidebar-shortcuts-large"> <button class="btn btn-success"> <i class="icon-signal"></i> </button> <button class="btn btn-info"> <i class="icon-pencil"></i> </button> <button class="btn btn-warning"> <i class="icon-group"></i> </button> <button class="btn btn-danger"> <i class="icon-cogs"></i> </button> </div> <div class="sidebar-shortcuts-mini" id="sidebar-shortcuts-mini"> <span class="btn btn-success"></span> <span class="btn btn-info"></span> <span class="btn btn-warning"></span> <span class="btn btn-danger"></span> </div> </div> <!-- #sidebar-shortcuts --> <ul class="nav nav-list"> <li class="active"> <a href="@Url.Action("Index","Admin")"> <i class="icon-dashboard"></i> <span class="menu-text"> 控制檯 </span> </a> </li> <li> <a href="#" class="dropdown-toggle"> <i class="icon-list"></i> <span class="menu-text"> 產品 </span> <b class="arrow icon-angle-down"></b> </a> <ul class="submenu"> <li> <a href="@Url.Action("Index","Product")"> <i class="icon-double-angle-right"></i> 產品管理 </a> </li> <li> <a href="@Url.Action("CategoryList","Product")"> <i class="icon-double-angle-right"></i> 分類管理 </a> </li> </ul> </li> <li> <a href="#" class="dropdown-toggle"> <i class="icon-desktop"></i> <span class="menu-text"> 用戶 </span> <b class="arrow icon-angle-down"></b> </a> <ul class="submenu"> <li> <a href="@Url.Action("Index","User")"> <i class="icon-double-angle-right"></i> 用戶管理 </a> </li> <li> <a href="@Url.Action("EditInfo","User")"> <i class="icon-double-angle-right"></i> 我的設置 </a> </li> </ul> </li> </ul><!-- /.nav-list --> <div class="sidebar-collapse" id="sidebar-collapse"> <i class="icon-double-angle-left" data-icon1="icon-double-angle-left" data-icon2="icon-double-angle-right"></i> </div> <script type="text/javascript"> try { ace.settings.check('sidebar', 'collapsed') } catch (e) { } </script> </div> <div class="main-content"> <div class="breadcrumbs" id="breadcrumbs"> <script type="text/javascript"> try { ace.settings.check('breadcrumbs', 'fixed') } catch (e) { } </script> <ul class="breadcrumb"> <li> <i class="icon-home home-icon"></i> <a href="@Url.Action("Index","Admin")">Home</a> </li> <li id="currentpart" class="active">控制檯</li> </ul><!-- .breadcrumb --> <div class="nav-search" id="nav-search"> <form class="form-search"> <span class="input-icon"> <input type="text" placeholder="Search ..." class="nav-search-input" id="nav-search-input" autocomplete="off" /> <i class="icon-search nav-search-icon"></i> </span> </form> </div><!-- #nav-search --> </div> <div class="page-content"> <div class="page-header"> <h1> <span>控制檯</span> <small> <i class="icon-double-angle-right"></i> <span>查看</span> </small> </h1> </div><!-- /.page-header --> <div class="row"> <div class="col-xs-12"> <!-- PAGE CONTENT BEGINS --> @RenderBody() <!-- PAGE CONTENT ENDS --> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.page-content --> </div><!-- /.main-content --> <div class="ace-settings-container" id="ace-settings-container"> <div class="btn btn-app btn-xs btn-warning ace-settings-btn" id="ace-settings-btn"> <i class="icon-cog bigger-150"></i> </div> <div class="ace-settings-box" id="ace-settings-box"> <div> <div class="pull-left"> <select id="skin-colorpicker" class="hide"> <option data-skin="default" value="#438EB9">#438EB9</option> <option data-skin="skin-1" value="#222A2D">#222A2D</option> <option data-skin="skin-2" value="#C6487E">#C6487E</option> <option data-skin="skin-3" value="#D0D0D0">#D0D0D0</option> </select> </div> <span> Choose Skin</span> </div> <div> <input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-navbar" /> <label class="lbl" for="ace-settings-navbar"> Fixed Navbar</label> </div> <div> <input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-sidebar" /> <label class="lbl" for="ace-settings-sidebar"> Fixed Sidebar</label> </div> <div> <input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-breadcrumbs" /> <label class="lbl" for="ace-settings-breadcrumbs"> Fixed Breadcrumbs</label> </div> <div> <input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-rtl" /> <label class="lbl" for="ace-settings-rtl"> Right To Left (rtl)</label> </div> <div> <input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-add-container" /> <label class="lbl" for="ace-settings-add-container"> Inside <b>.container</b> </label> </div> </div> </div><!-- /#ace-settings-container --> </div><!-- /.main-container-inner --> <a href="#" id="btn-scroll-up" class="btn-scroll-up btn btn-sm btn-inverse"> <i class="icon-double-angle-up icon-only bigger-110"></i> </a> </div><!-- /.main-container --> <!-- basic scripts --> <!--[if !IE]> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <![endif]--> <!--[if IE]> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <![endif]--> <!--[if IE]> <script type="text/javascript"> window.jQuery || document.write("<script src='~/Content/Js/jquery-1.10.2.min.js'>"+"<"+"/script>"); </script> <![endif]--> <script type="text/javascript"> if ("ontouchend" in document) document.write("<script src='~/Content/Js/jquery.mobile.custom.min.js'>" + "<" + "/script>"); </script> <script src="~/Content/Js/bootstrap.min.js"></script> <script src="~/Content/Js/typeahead-bs2.min.js"></script> <!-- page specific plugin scripts --> <script src="~/Content/Js/jquery-ui-1.10.3.custom.min.js"></script> <script src="~/Content/Js/jquery.ui.touch-punch.min.js"></script> <script src="~/Content/Js/bootbox.min.js"></script> <!-- ace scripts --> <script src="~/Content/Js/ace-elements.min.js"></script> <script src="~/Content/Js/ace.min.js"></script> <!-- inline scripts related to this page --> <script type="text/javascript"> jQuery(function ($) { /* initialize the external events -----------------------------------------------------------------*/ $('#external-events div.external-event').each(function () { // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) // it doesn't need to have a start or end var eventObject = { title: $.trim($(this).text()) // use the element's text as the event title }; // store the Event Object in the DOM element so we can get to it later $(this).data('eventObject', eventObject); // make the event draggable using jQuery UI $(this).draggable({ zIndex: 999, revert: true, // will cause the event to go back to its revertDuration: 0 // original position after the drag }); }); /* initialize the calendar -----------------------------------------------------------------*/ }) </script> <div style="display:none"><script src='http://v7.cnzz.com/stat.php?id=155540&web_id=155540' language='JavaScript' charset='gb2312'></script></div> <script src="~/Content/Js/niqiu.js"></script> @RenderSection("scripts", required: false) </body></html>
2、引入Jqgridjquery
若是你的表格比較多,建議你作一個分部試圖,重複利用,個人partview JqgridInit.cshtml 以下,web
<link rel="stylesheet" href="~/Content/CSS/ui.jqgrid.css" /> <script src="~/Content/Js/jqGrid/jquery.jqGrid.min.js"></script> <script src="~/Content/Js/jqGrid/i18n/grid.locale-en.js"></script> <style> #pager2 { height: 40px; } .FormGrid ,#DelTb1_list2{ position: relative; overflow: visible; float: left; } .ui-jqgrid-sortable { height: 30px !important; } </style> <table id="list"></table> <div id="pager"></div> <span class="errorinfo"></span>
list用來呈現數據,pager用來分頁,errorinfo用來提示錯誤。jqgrid,涉及的配置比較多。須要後臺代碼的全面的支持,因此在介紹配置以前,先介紹下模型和倉庫。ajax
1.Product: 咱們須要呈現的一個是一個產品,有不少不一樣的價格及其餘,這些都將成爲表格的列名。數據庫
public class Product { /// <summary> /// Gets or sets the id. /// </summary> /// <value>The id.</value> [Key] public int ProductId { get; set; } /// <summary> /// 直接作型號處理 /// </summary> public string ProductName { get; set; } /// <summary> /// Gets or sets the category. /// </summary> /// <value>The category.</value> public string Category { get; set; } /// <summary> /// Gets or sets the brand. /// </summary> /// <value>The brand.</value> public string Brand { get; set; } public string Size { get; set; } /// <summary> /// Gets or sets the 規格. /// </summary> /// <value>The standard.</value> public string Standard { get; set; } /// <summary> /// 專櫃 /// </summary> public decimal ZhuanGui { get; set; } /// <summary> /// Gets or sets the 莎莎 price. /// </summary> /// <value>The sa sa price.</value> public decimal SaSaPrice { get; set; } /// <summary> /// Gets or sets the 卓越 price. /// </summary> /// <value>The zhuoyue price.</value> public decimal ZhuoyuePrice { get; set; } /// <summary> /// Gets or sets the 卡萊美 price. /// </summary> /// <value>The ka lai price.</value> public decimal KaLaiPrice { get; set; } /// <summary> /// 雅施 /// </summary> public decimal YaShi { get; set; } /// <summary> /// Gets or sets the 萬寧 price. /// </summary> /// <value>The wanning price.</value> public decimal WanningPrice { get; set; } /// <summary> /// Gets or sets the 屈臣氏 price. /// </summary> /// <value>The quchengshi price.</value> public decimal QuchengshiPrice { get; set; } /// <summary> /// Gets or sets the 藥店 price. /// </summary> /// <value>The drugstore price.</value> public decimal DrugstorePrice { get; set; } /// <summary> /// Gets or sets the others. /// </summary> /// <value>The others.</value> public string Others { get; set; } /// <summary> /// Gets or sets the create time. /// </summary> /// <value>The create time.</value> public DateTime CreateTime { get; set; } public string ImgUrl { get; set; } public Product() { CreateTime = DateTime.Now; } }
2.ProductRepository (倉庫真的很好,獨立了業務邏輯,可測試,複用快),add、remove、update不用講了,主要講一講排序。
1)排序查詢的意義在於根據不一樣的屬性進行排序。
public class ProductRepository:IProductRepository { private readonly XNDb _db = new XNDb(); //.... public IEnumerable<Product> Find(string sort = "asc", string property = "ProductName", int skip = 0, int take = 10) { var propertyInfo = typeof(Product).GetProperty(property);//反射出這個屬性 Func<Product, object> expn = e => propertyInfo.GetValue(e, null);//委託 var rawpros = _db.Products; IEnumerable<Product> pros = sort == "asc" ? rawpros.OrderBy(expn).Skip(skip).Take(take).ToArray() : rawpros.OrderByDescending(expn).Skip(skip).Take(take).ToArray();//分頁排序 return pros; }
//.... }
在只考慮排序的狀況下,控制器的代碼就相對簡單:
public JsonResult GetAllPros( string sord = "asc", string sidx = "ProductName",int page = 1, int rows = 10) { var pros = _repository.Find(sord, switchSidx(sidx), (page - 1) * rows, rows); var objpros = new List<object>(pros); var jsonData = JqGridModel.GridData(page, rows, _repository.Count, objpros); return Json(jsonData, JsonRequestBehavior.AllowGet); }
若是涉及到複雜些的查詢,等於不等於,包含之類的,會多了後面mark部分的參數,這裏我用很笨的辦法實現了單列查詢,也就就是根據包含、等於、不等於先查出來,再排序,若是是多重查詢,你們能夠參考博客:http://www.codeproject.com/Articles/58357/Using-jqGrid-s-search-toolbar-with-multiple-filter
public JsonResult GetAllPros( string sord = "asc", string sidx = "ProductName",int page = 1, int rows = 10, bool _search = false,string searchField="", string searchOper="", string searchString="") { var rawpros = GetRawPros(_search, searchField, searchOper, searchString); var propertyInfo = typeof(Product).GetProperty(switchSidx(sidx)); Func<Product, object> expn = e => propertyInfo.GetValue(e, null); var enumerable = rawpros as Product[] ?? rawpros.ToArray(); IEnumerable<Product> pros = sord == "asc" ? enumerable.OrderBy(expn).Skip((page - 1) * rows).Take(rows).ToArray() : enumerable.OrderByDescending(expn).Skip((page - 1) * rows).Take(rows).ToArray(); var objpros = new List<object>(pros); var jsonData = JqGridModel.GridData(page, rows, enumerable.Count(), objpros); return Json(jsonData, JsonRequestBehavior.AllowGet); }
須要說明的是,這裏的switchsidx就是將中文列名轉爲對象屬性名,一堆case語句,而後JqgridModel的getdata,是jqgrid定義好的一種json格式,包含了每頁行數和總頁數等信息,由於前段的每頁行數是能夠變化的。
public class JqGridModel { /// <summary> /// Grids the data. /// </summary> /// <param name="page1">當前頁數.</param> /// <param name="rows">每頁顯示數目.</param> /// <param name="total"></param> /// <param name="objects">集合對象</param> /// <returns>System.Object.</returns> public static object GridData(int page1, int rows, int total, IEnumerable<object> objects) { int pageSize = rows; var totalPages = (int)Math.Ceiling((float)total / pageSize); //可根據具體狀況,實現排序。 var jsonData = new { total = totalPages, page = page1, records = total, rows = objects.ToArray() }; return jsonData; } }
2)須要一個新增:(記住返回json的時候要allowGet,否則可能形成添加失敗,其餘地方同理)
[HttpPost] public ActionResult Create(Product product) { _repository.Add(product); var fu = _repository.FindByName(product.ProductName); return Json(fu, JsonRequestBehavior.AllowGet); }
3)編輯和刪除:這裏的編輯有三個參數,一個對象,一個操做,一個id,id是個雞肋,竟然返回的是table的行號(會隨着排序變化),oper多是add,del,這裏我只用到了edit,del傳回的id嘗試改變它爲對象的id,但沒成功。用了因外一種方式實現刪除。
[HttpPost] public ActionResult Edit(Product pro, string oper, int id) { if (oper == "edit") { _repository.Update(pro); pro.CreateTime = DateTime.Now; } return Json(pro, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult Delete(int id) { _repository.Remove(id); return Json(id, JsonRequestBehavior.AllowGet); ; }
有了這四個方法就ok了。下面來說配置。先打個預防針,主要關心兩個方法,一個設置table,一個設置分頁。而後代碼比較長..... 但願沒有打消你駕馭它的渴望。
所有控制器代碼:包含了分類的一些,道理同樣
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Web; using System.Web.Mvc; using XNManage.Common; using XNManage.Models; using XNManage.Repository; using XNManage.ViewModel; namespace XNManage.Controllers { public class ProductController : Controller { // // GET: /Product/ private readonly IProductRepository _repository; private IEnumerable<CategoryViewModel> _categoryViewModels = new List<CategoryViewModel>(); public ProductController(IProductRepository repository) { _repository = repository; } #region 產品 [LoginValid] public ActionResult Index() { //CategoryInit(); //ProductsInits(); return View(); } public JsonResult GetAllPros( string sord = "asc", string sidx = "ProductName",int page = 1, int rows = 10, bool _search = false,string searchField="", string searchOper="", string searchString="") { var rawpros = GetRawPros(_search, searchField, searchOper, searchString); var propertyInfo = typeof(Product).GetProperty(switchSidx(sidx)); Func<Product, object> expn = e => propertyInfo.GetValue(e, null); var enumerable = rawpros as Product[] ?? rawpros.ToArray(); IEnumerable<Product> pros = sord == "asc" ? enumerable.OrderBy(expn).Skip((page - 1) * rows).Take(rows).ToArray() : enumerable.OrderByDescending(expn).Skip((page - 1) * rows).Take(rows).ToArray(); var objpros = new List<object>(pros); var jsonData = JqGridModel.GridData(page, rows, enumerable.Count(), objpros); return Json(jsonData, JsonRequestBehavior.AllowGet); } private IEnumerable<Product> GetRawPros(bool search = false, string searchField = "", string searchOper = "", string searchString = "") { var rawpros = _repository.FindAll(); if (!search) return rawpros; switch (switchSidx(searchField)) { case "ProductName": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.ProductName.Contains(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.ProductName == searchString); break; case "ne": rawpros = rawpros.Where(n => n.ProductName != searchString); break; default: rawpros = rawpros.Where(n => n.ProductName.Contains(searchString)); break; } break; case "Category": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.Category.Contains(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.Category == searchString); break; case "ne": rawpros = rawpros.Where(n => n.Category != searchString); break; default: rawpros = rawpros.Where(n => n.Category.Contains(searchString)); break; } break; case "Brand": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.Brand.Contains(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.Brand == searchString); break; case "ne": rawpros = rawpros.Where(n => n.Brand != searchString); break; default: rawpros = rawpros.Where(n => n.Brand.Contains(searchString)); break; } break; case "SaSaPrice": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.SaSaPrice >= Convert.ToDecimal(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.SaSaPrice == Convert.ToDecimal(searchString)); break; case "ne": rawpros = rawpros.Where(n => n.SaSaPrice != Convert.ToDecimal(searchString)); break; } break; case "ZhuanGui": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.ZhuanGui >= Convert.ToDecimal(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.ZhuanGui == Convert.ToDecimal(searchString)); break; case "ne": rawpros = rawpros.Where(n => n.ZhuanGui != Convert.ToDecimal(searchString)); break; } break; case "YaShi": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.YaShi >= Convert.ToDecimal(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.YaShi == Convert.ToDecimal(searchString)); break; case "ne": rawpros = rawpros.Where(n => n.YaShi != Convert.ToDecimal(searchString)); break; } break; case "ZhuoyuePrice": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.ZhuoyuePrice >= Convert.ToDecimal(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.ZhuoyuePrice == Convert.ToDecimal(searchString)); break; case "ne": rawpros = rawpros.Where(n => n.ZhuoyuePrice != Convert.ToDecimal(searchString)); break; } break; case "WanningPrice": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.WanningPrice >= Convert.ToDecimal(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.WanningPrice == Convert.ToDecimal(searchString)); break; case "ne": rawpros = rawpros.Where(n => n.WanningPrice != Convert.ToDecimal(searchString)); break; } break; case "QuchengshiPrice": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.QuchengshiPrice >= Convert.ToDecimal(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.QuchengshiPrice == Convert.ToDecimal(searchString)); break; case "ne": rawpros = rawpros.Where(n => n.QuchengshiPrice != Convert.ToDecimal(searchString)); break; } break; case "DrugstorePrice": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.DrugstorePrice >= Convert.ToDecimal(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.DrugstorePrice == Convert.ToDecimal(searchString)); break; case "ne": rawpros = rawpros.Where(n => n.DrugstorePrice != Convert.ToDecimal(searchString)); break; } break; case "Others": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.Others.Contains(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.Others ==searchString); break; case "ne": rawpros = rawpros.Where(n => n.Others !=searchString); break; } break; case "KaLaiPrice": switch (searchOper) { case "cn": rawpros = rawpros.Where(n => n.KaLaiPrice >= Convert.ToDecimal(searchString)); break; case "eq": rawpros = rawpros.Where(n => n.KaLaiPrice == Convert.ToDecimal(searchString)); break; case "ne": rawpros = rawpros.Where(n => n.KaLaiPrice != Convert.ToDecimal(searchString)); break; } break; default: break; } return rawpros; } /* public JsonResult GetData(GridSettings grid) { var query = _repository.FindAll(); //filtring if (grid.IsSearch) { //And if (grid.Where.groupOp == "AND") foreach (var rule in grid.Where.rules) query = query.Where<Product>( rule.field, rule.data, (WhereOperation)StringEnum.Parse(typeof(WhereOperation), rule.op)); else { //Or var temp = (new List<Product>()).AsQueryable(); foreach (var rule in grid.Where.rules) { var t = query.Where<Product>( rule.field, rule.data, (WhereOperation)StringEnum.Parse(typeof(WhereOperation), rule.op)); temp = temp.Concat<Product>(t); } //remove repeating records query = temp.Distinct<Product>(); } } //sorting query = query.OrderBy<Product>(grid.SortColumn, grid.SortOrder); //count var count = query.Count(); //paging var data = query.Skip((grid.PageIndex - 1) * grid.PageSize).Take(grid.PageSize).ToArray(); //converting in grid format var result = new { total = (int)Math.Ceiling((double)count / grid.PageSize), page = grid.PageIndex, records = count, rows = data.ToArray() }; //convert to JSON and return to client return Json(result, JsonRequestBehavior.AllowGet); } */ //這個函數其實沒必要要!index中能夠寫英文。列名和index沒有關係 private string switchSidx(string sidx) { switch (sidx) { case "型號": return "ProductName"; case "類別": return "Category"; case "品牌": return "Brand"; case "規格": return "Standard"; case "專櫃": return "ZhuanGui"; case "莎莎": return "SaSaPrice"; case "雅施": return "YaShi"; case "卓越": return "ZhuoyuePrice"; case "卡萊美": return "KaLaiPrice"; case "萬寧": return "WanningPrice"; case "屈臣氏": return "QuchengshiPrice"; case "藥店": return "DrugstorePrice"; case "其餘": return "Others"; case "描述": return "Description"; case "更新時間": return "CreateTime"; default: return "ProductName"; } } public string CategorySelectList() { var cs = _repository.AllCategories(); var sb=new StringBuilder("<select>"); foreach (var category in cs) { sb.Append(string.Format("<option value='{0}' >{1}</option>", category.CategoryName, category.CategoryName)); } sb.Append("</select>"); return sb.ToString(); } [HttpPost] public ActionResult Edit(Product pro, string oper, int id) { if (oper == "edit") { _repository.Update(pro); pro.CreateTime = DateTime.Now; } return Json(pro, JsonRequestBehavior.AllowGet); } // // POST: /Product/Create [HttpPost] public ActionResult Create(Product product) { _repository.Add(product); var fu = _repository.FindByName(product.ProductName); return Json(fu, JsonRequestBehavior.AllowGet); } // // POST: /Product/Delete/5 [HttpPost] public ActionResult Delete(int id) { _repository.Remove(id); return Json(id); } private void CategoryInit() { if (!_repository.AllCategories().Any()) { _repository.AddCategorie(new Category { CategoryName = "護膚品", Description = "春天女生護膚專用" }); _repository.AddCategorie(new Category() { CategoryName = "防曬", Description = "夏日噴霧防曬" } ); } } private void ProductsInits() { if (!_repository.FindAll().Any()) { _repository.Add(new Product() { ProductName = "水寶寶", Others = "防曬", SaSaPrice = 78, DrugstorePrice = 98 }); } } #endregion #region 分類 private IEnumerable<CategoryViewModel> initCategoryViewModels() { if (!_categoryViewModels.Any()) { var cas = _repository.AllCategories(); _categoryViewModels = cas.Select(n => new CategoryViewModel() { CategoryId = n.CategoryId, CategoryName = n.CategoryName, Description = n.Description, ProductCount = _repository.GetCategorieProducts(n.CategoryName).Count() }); } return _categoryViewModels; } public JsonResult GetAllCategorys(string sord = "asc", string sidx = "CategoryName", int page = 1, int rows = 10) { IList<object> pros = new List<object>(FindCategoryViewModels(sord, sidx, (page - 1) * rows, rows)); var jsonData = JqGridModel.GridData(page, rows, initCategoryViewModels().Count(), pros); return Json(jsonData, JsonRequestBehavior.AllowGet); } public IEnumerable<CategoryViewModel> FindCategoryViewModels(string sort = "asc", string property = "CategoryName", int skip = 0, int take = 10) { var propertyInfo = typeof(CategoryViewModel).GetProperty(property); Func<CategoryViewModel, object> expn = e => propertyInfo.GetValue(e, null); var fakeProfiles =initCategoryViewModels(); IEnumerable<CategoryViewModel> pros = sort == "asc" ? fakeProfiles.OrderBy(expn).Skip(skip).Take(take).ToArray() : fakeProfiles.OrderByDescending(expn).Skip(skip).Take(take).ToArray(); return pros; } public ActionResult EditCategory(CategoryViewModel model,string oper, int id) { if (oper == "edit") { var ca = new Category() { CategoryId = model.CategoryId, CategoryName = model.CategoryName, Description = model.Description, }; _repository.UpdateCategorie(ca); } return Json(model, JsonRequestBehavior.AllowGet); } public ActionResult CategoryList() { return View(); } [HttpPost] public ActionResult CreateCategory(Category category) { _repository.AddCategorie(category); var fu = _repository.FindCategorieById(category.CategoryId); var cm = new CategoryViewModel() { CategoryName = fu.CategoryName, CategoryId = fu.CategoryId, Description = fu.Description, ProductCount = _repository.GetCategorieProducts(fu.CategoryName).Count() }; return Json(cm, JsonRequestBehavior.AllowGet); } public ActionResult DeletCategory(int id) { _repository.RemoveCategorie(id); return Json(1); } public PartialViewResult JqgridInit() { return PartialView(); } public JsonResult GetChartData() { var cms = initCategoryViewModels().ToList(); var count =_repository.Count; var chartDatas = cms.Select(n => new ChartData { label = n.CategoryName, data = Math.Round((double)n.ProductCount / count, 3), }).ToArray(); return Json(chartDatas, JsonRequestBehavior.AllowGet); } #endregion } }
1)table的設置
jQuery("#list").jqGrid({ url: '/Product/GetAllPros', //獲取數據源 datatype: "json", colNames: ['操做', 'ProductId', '類別', '品牌', '型號', '規格', '專櫃', '莎莎', '卓越', '卡萊美', '雅施', '萬寧', '屈臣氏', '藥店', '其餘', '更新時間'], //定義列名 colModel: [ //name 是對應咱們的Product模型的屬性,Index能夠爲中文也能夠爲英文,沒必要於上面colnames對應,順序對就好了。查詢的時候傳到後臺的是index。 { name: 'myac', index: '操做', width: 60, fixed: true, sortable: false, resize: false, formatter: 'actions', formatoptions: { keys: true, delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback, }, } },
//詳細的字段配置信息請見博客:http://www.cnblogs.com/huozhicheng/archive/2012/11/20/2778649.html { name: 'ProductId', index: 'ProductId', hidden: true, editable: true }, { name: 'Category', index: '類別', editable: true, edittype: 'select', editoptions: { dataUrl: "/Product/CategorySelectList" }, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'Brand', index: '品牌', editable: true, editrules: { required: false }, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'ProductName', index: '型號', editable: true, editrules: { required: true }, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'Standard', index: '規格', editable: true, edittype: 'textarea', searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'ZhuanGui', index: '專櫃', editable: true, width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } },//formatter: 'integer', formatter: 'integer', { name: 'SaSaPrice', index: '莎莎', editable: true,width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'ZhuoyuePrice', index: '卓越', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'KaLaiPrice', index: '卡萊美', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'YaShi', index: '雅施', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'WanningPrice', index: '萬寧', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'QuchengshiPrice', index: '屈臣氏', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'DrugstorePrice', index: '藥店', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'Others', index: '其餘', editable: true, edittype: 'textarea', searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'CreateTime', index: '更新時間', width: 200, formatter: 'date', //時間格式顯示 formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s', searchoptions: { sopt: ['eq', 'ne', 'cn'] } } } ], rowNum: 10, rowList: [10, 20, 30], sortorder: "asc", pager: '#pager2', sortname: 'ProductName', viewrecords: true, caption: "產品明細", autowidth: true, multiselect: true, height: 180, gridComplete: function () { var icons = $(".ui-icon-trash");//隱藏刪除鍵 icons.hide();//我隱藏了刪除鍵 由於id的問題 //var ids = jQuery("#list2").jqGrid('getDataIDs'); //for (var i = 0; i < ids.length; i++) { // be = "<span class='ui-icon ui-icon-pencil'></span>";//修改 // se = "<span class='ui-icon ui-icon-trash'></span>";//刪除 // ce = "<span class='icon-ok ui-icon'></span>";//刪除 // jQuery("#list2").jqGrid('setRowData', ids[i], { act: be + se + ce }); //}
//這個部分是能夠添加定義的按鈕,本身用腳本去實現。
}, loadComplete: function () { $("#grid-table").hide(); var table = this; enableTooltips(table); updatePagerIcons(table); }, editurl: "/Product/Edit", //編輯的地址 操做欄觸發的操做都會丟到這個action中響應。 add edit del //改變傳id的方法無效!!!! serializeDelData: function (postdata) { var rowdata = jQuery('#list2').getRowData(postdata.id); return { id: postdata.id, oper: postdata.oper, user: rowdata }; } //edit del });
造成樣子以下:
colModel涉及的配置較多,不一樣的字段有不一樣的呈現,能夠參考博客 http://www.cnblogs.com/huozhicheng/archive/2012/11/20/2778649.html
2)pager 用來造成分頁和集成一些操做。
jQuery("#list").jqGrid('navGrid', '#pager2', {
//調整ui 也就是咱們看到的:,但這個刪除圖標是我代碼加上去的。 edit: true, editicon: 'icon-pencil blue', add: true, addicon: 'icon-plus-sign purple', del: false, delicon: 'icon-trash red', search: true, searchicon: 'icon-search orange', refresh: true, refreshicon: 'icon-refresh green', view: false, viewicon: 'icon-zoom-in grey', }, { //eidt url: '/Product/Edit', mtype: 'POST', afterSubmit: function (xhr, postdata) { var id = $("#list2").jqGrid('getGridParam', 'selrow'); jQuery("#list2").jqGrid('setRowData', id, postdata); }, closeAfterEdit: true, closeOnEscape: true }, { //add recreateForm: true, url: '/Product/Create', mtype: 'POST', afterSubmit: function (xhr, postdata) { var id = $("#list2").jqGrid('getGridParam', 'selrow'); jQuery("#list2").jqGrid('addRowData', postdata.Id, postdata); return [true, 'successfule!', false]; }, closeAfterAdd: true }, { //delete 此處無效 recreateForm: true, url: '/Product/Delete', mtype: 'POST', beforeShowForm: function (e) { var form = $(e[0]); if (form.data('styled')) return false; form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />'); styleDeleteForm(form); form.data('styled', true); return true; }, afterSubmit: function (xhr, postdata) { var consoleDlg = $("#list2"); var selectedRowIds = $("#list2").jqGrid("getGridParam", "selarrrow"); var len = selectedRowIds.length; for (var i = 0; i < len ; i++) { $("#list2").jqGrid("delRowData", selectedRowIds[0]); } }, closeAfterDel: true }, { //search recreateForm: true, afterShowSearch: function(e){ var form = $(e[0]); form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />') styleSearchForm(form); }, afterRedraw: function(){ styleSearchFilters($(this)); } , // multipleSearch: true, closeAfterSearch: true }, { //view } );
在下面加入按鈕的方法以及執行刪除:jquery2.0中的綁定寫法有些不一樣,也就是on的用法。
function updatePagerIcons() { //... var x = $("#pager2_left").find("#coco"); if (x.length == 0) { $("#pager2_left table tbody>tr").prepend("<td class='ui-pg-button ui-corner-all' title data-original-title='Remove a row'><div id='coco' class='ui-pg-div'>" + "<span class='ui-icon icon-trash blue'></span></div></td>"); } } //綁定事件 執行刪除 $("#pager2_left table tbody>tr").on("click", '#coco', function () { var selectedRowIds = $("#list2").jqGrid("getGridParam", "selarrrow"); var len = selectedRowIds.length; if (len != 0) { if (confirm("肯定要刪除選中項?")) { for (var i = 0; i < len; i++) { var rowData = $("#list2").jqGrid('getRowData', selectedRowIds[i]); $.post('/Product/Delete', { id: rowData.ProductId }, function (data) { $("#list2").jqGrid("delRowData", selectedRowIds[0]); }); } } } else { $.infoShow("未勾選", 0); } });
造成這個樣子:
所有前臺代碼:
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } @Html.Partial("JqgridInit") <script> $(function () { $(".page-header h1 span,#currentpart").html("產品"); $(".page-header h1 small span").html("產品管理"); $(".nav-list>li:eq(1)").addClass("active").siblings().removeClass("active"); jQuery("#list2").jqGrid({ url: '/Product/GetAllPros', datatype: "json", colNames: ['操做', 'ProductId', '類別', '品牌', '型號', '規格', '專櫃', '莎莎', '卓越', '卡萊美', '雅施', '萬寧', '屈臣氏', '藥店', '其餘', '更新時間'], colModel: [ { name: 'myac', index: '操做', width: 60, fixed: true, sortable: false, resize: false, formatter: 'actions', formatoptions: { keys: true, delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback, },//改變原來的樣式 msg: '您肯定要刪除這條記錄?</span> searchoptions: { sopt: ['eq', 'ne', 'cn'] }, } // name: 'act', index: 'act', width: 75, sortable: false }, { name: 'ProductId', index: 'ProductId', hidden: true, editable: true }, { name: 'Category', index: '類別', editable: true, edittype: 'select', editoptions: { dataUrl: "/Product/CategorySelectList" }, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'Brand', index: '品牌', editable: true, editrules: { required: false }, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'ProductName', index: '型號', editable: true, editrules: { required: true }, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'Standard', index: '規格', editable: true, edittype: 'textarea', searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'ZhuanGui', index: '專櫃', editable: true, width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } },//formatter: 'integer', formatter: 'integer', { name: 'SaSaPrice', index: '莎莎', editable: true,width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'ZhuoyuePrice', index: '卓越', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'KaLaiPrice', index: '卡萊美', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'YaShi', index: '雅施', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'WanningPrice', index: '萬寧', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'QuchengshiPrice', index: '屈臣氏', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'DrugstorePrice', index: '藥店', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'Others', index: '其餘', editable: true, edittype: 'textarea', searchoptions: { sopt: ['eq', 'ne', 'cn'] } }, { name: 'CreateTime', index: '更新時間', width: 200, formatter: 'date', formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s', searchoptions: { sopt: ['eq', 'ne', 'cn'] } } } ], rowNum: 10, rowList: [10, 20, 30], sortorder: "asc", pager: '#pager2', sortname: 'ProductName', viewrecords: true, caption: "產品明細", autowidth: true, multiselect: true, height: 180, gridComplete: function () { var icons = $(".ui-icon-trash");//隱藏刪除鍵 icons.hide(); //var ids = jQuery("#list2").jqGrid('getDataIDs'); //for (var i = 0; i < ids.length; i++) { // be = "<span class='ui-icon ui-icon-pencil'></span>";//修改 // se = "<span class='ui-icon ui-icon-trash'></span>";//刪除 // ce = "<span class='icon-ok ui-icon'></span>";//刪除 // jQuery("#list2").jqGrid('setRowData', ids[i], { act: be + se + ce }); //} }, loadComplete: function () { $("#grid-table").hide(); var table = this; enableTooltips(table); updatePagerIcons(table); }, editurl: "/Product/Edit", //無效!!!! serializeDelData: function (postdata) { var rowdata = jQuery('#list2').getRowData(postdata.id); return { id: postdata.id, oper: postdata.oper, user: rowdata }; } //edit del }); jQuery("#list2").jqGrid('navGrid', '#pager2', { edit: true, editicon: 'icon-pencil blue', add: true, addicon: 'icon-plus-sign purple', del: false, delicon: 'icon-trash red', search: true, searchicon: 'icon-search orange', refresh: true, refreshicon: 'icon-refresh green', view: false, viewicon: 'icon-zoom-in grey', }, { //eidt url: '/Product/Edit', mtype: 'POST', afterSubmit: function (xhr, postdata) { var id = $("#list2").jqGrid('getGridParam', 'selrow'); jQuery("#list2").jqGrid('setRowData', id, postdata); }, closeAfterEdit: true, closeOnEscape: true }, { //add recreateForm: true, url: '/Product/Create', mtype: 'POST', afterSubmit: function (xhr, postdata) { var id = $("#list2").jqGrid('getGridParam', 'selrow'); jQuery("#list2").jqGrid('addRowData', postdata.Id, postdata); return [true, 'successfule!', false]; }, closeAfterAdd: true }, { //delete recreateForm: true, url: '/Product/Delete', mtype: 'POST', beforeShowForm: function (e) { var form = $(e[0]); if (form.data('styled')) return false; form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />'); styleDeleteForm(form); form.data('styled', true); return true; }, afterSubmit: function (xhr, postdata) { var consoleDlg = $("#list2"); var selectedRowIds = $("#list2").jqGrid("getGridParam", "selarrrow"); var len = selectedRowIds.length; for (var i = 0; i < len ; i++) { $("#list2").jqGrid("delRowData", selectedRowIds[0]); } }, closeAfterDel: true }, { //search recreateForm: true, afterShowSearch: function(e){ var form = $(e[0]); form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />') styleSearchForm(form); }, afterRedraw: function(){ styleSearchFilters($(this)); } , // multipleSearch: true, closeAfterSearch: true }, { //view } ); //添加註釋 function enableTooltips(table) { $('.navtable .ui-pg-button').tooltip({ container: 'body' }); $(table).find('.ui-pg-div').tooltip({ container: 'body' }); } function beforeDeleteCallback(e) { var form = $(e[0]); if (form.data('styled')) return false; form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />'); styleDeleteForm(form); form.data('styled', true); return true; } //修改 刪除form的樣式 function styleDeleteForm(form) { var buttons = form.next().find('.EditButton .fm-button'); buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon buttons.eq(0).addClass('btn-danger').prepend('<i class="icon-trash"></i>'); buttons.eq(1).prepend('<i class="icon-remove"></i>'); } //更新分頁圖標 function updatePagerIcons() { var replacement = { 'ui-icon-seek-first': 'icon-double-angle-left bigger-140', 'ui-icon-seek-prev': 'icon-angle-left bigger-140', 'ui-icon-seek-next': 'icon-angle-right bigger-140', 'ui-icon-seek-end': 'icon-double-angle-right bigger-140' }; $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () { var icon = $(this); var $class = $.trim(icon.attr('class').replace('ui-icon', '')); if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]); }); var x = $("#pager2_left").find("#coco"); if (x.length == 0) { $("#pager2_left table tbody>tr").prepend("<td class='ui-pg-button ui-corner-all' title data-original-title='Remove a row'><div id='coco' class='ui-pg-div'>" + "<span class='ui-icon icon-trash blue'></span></div></td>"); } } function styleSearchForm(form) { var dialog = form.closest('.ui-jqdialog'); var buttons = dialog.find('.EditTable') buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'icon-retweet'); buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'icon-comment-alt'); buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'icon-search'); } function styleSearchFilters(form) { form.find('.delete-rule').val('X'); form.find('.add-rule').addClass('btn btn-xs btn-primary'); form.find('.add-group').addClass('btn btn-xs btn-success'); form.find('.delete-group').addClass('btn btn-xs btn-danger'); } //綁定事件 執行刪除 $("#pager2_left table tbody>tr").on("click", '#coco', function () { var selectedRowIds = $("#list2").jqGrid("getGridParam", "selarrrow"); var len = selectedRowIds.length; if (len != 0) { if (confirm("肯定要刪除選中項?")) { for (var i = 0; i < len; i++) { var rowData = $("#list2").jqGrid('getRowData', selectedRowIds[i]); $.post('/Product/Delete', { id: rowData.ProductId }, function (data) { $("#list2").jqGrid("delRowData", selectedRowIds[0]); }); } } } else { $.infoShow("未勾選", 0); } }); }); </script>
至此基本告成,還有些能夠優化。
若是本文對你有幫助,請霸氣的支持下 :) tks~
須要源碼的同窗,請戳下行。備註:數據庫是EntityFramework + CE4.0,帳戶密碼都是:admin
http://pan.baidu.com/s/1eSx6E0E 年輕的諸君,記得點贊留名~
模板源碼:http://pan.baidu.com/s/1gdEGg2v
參考博客:
參數設定 http://www.cnblogs.com/younggun/archive/2012/08/27/2657922.html
jqgridDemo:http://www.trirand.com/blog/jqgrid/jqgrid.html
多重查詢:http://www.codeproject.com/Articles/58357/Using-jqGrid-s-search-toolbar-with-multiple-filter
其餘後臺模板:http://www.tystudio.net/2013/03/11/back-manage-system-template/