Asp.Net MVC中使用ACE模板之Jqgrid

开发 后端
第一次看到ACE模板,有种感动,有种相见恨晚的感觉,于是迅速来研究。它本身是基于bootstrap和jqueryui,但更nice,整合之后为后台开发节省了大量时间。

第一次看到ACE模板,有种感动,有种相见恨晚的感觉,于是迅速来研究。它本身是基于bootstrap和jqueryui,但更nice,整合之后为后台开发节省了大量时间。 发现虽然不是完美,整体效果还是不错,特此分享给园友。这一节先讲其中的Jqgrid。按照国际惯例,先上两张图。

   

集成了button,form,treeview以及日历,时间轴、chart等控件,非常丰富。下面是Jqgrid在MVC中的使用。

jqgrid的加载,排序,查找都是基于后台方法,不是在内存中完成,但也有一些小坑。下面一一道来。

一、引入ace模板

 ace本身考虑了对ie的兼容,加上bootstrap和jqueryui所以引入的样式和脚本文件比较多。我拿掉了一下googlefont的链接,请求太慢了,你懂的。现在MVC最关心的就是RenderBody的位置。在page-content下的Row,也可以将page-header放入子页面中去,自己多写几个元素,这个就在于你自己的选择了。

  1. <div class="page-content"> 
  2.                         <div class="page-header"> 
  3.                             <h1> 
  4.                                 <span>控制台</span> 
  5.                                 <small> 
  6.                                     <i class="icon-double-angle-right"></i> 
  7.                                     <span>查看</span> 
  8.                                 </small> 
  9.                             </h1> 
  10.                         </div><!-- /.page-header --> 
  11.  
  12.                         <div class="row"> 
  13.                             <div class="col-xs-12"> 
  14.                                 <!-- PAGE CONTENT BEGINS --> 
  15.                                  @RenderBody()  
  16.                                 <!-- PAGE CONTENT ENDS --> 
  17.                             </div><!-- /.col --> 
  18.                         </div><!-- /.row --> 
  19.                     </div><!-- /.page-content --> 

全部的layout.cshtml

  1. <!DOCTYPE html> 
  2. <html > 
  3. <head> 
  4.     <meta charset="utf-8" /> 
  5.     <meta name="viewport" content="width=device-width" /> 
  6.       <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
  7.     <title>@ViewBag.Title</title> 
  8.       
  9.     <link href="~/Content/CSS/bootstrap.min.css" rel="stylesheet" /> 
  10.     <link rel="stylesheet" href="~/Content/CSS/font-awesome.min.css" /> 
  11.     <script src="~/Content/Js/jquery-2.0.3.min.js"></script> 
  12.     <link href="~/Content/CSS/niqiu.css" rel="stylesheet" /> 
  13.     <!--[if IE 7]> 
  14.           <link rel="stylesheet" href="~/Content/CSS/font-awesome-ie7.min.css" /> 
  15.         <![endif]--> 
  16.  
  17.         <!-- page specific plugin styles --> 
  18.  
  19.         <!-- ace styles --> 
  20.  
  21.         <link rel="stylesheet" href="~/Content/CSS/ace.min.css" /> 
  22.         <link rel="stylesheet" href="~/Content/CSS/ace-rtl.min.css" /> 
  23.         <link rel="stylesheet" href="~/Content/CSS/ace-skins.min.css" /> 
  24.          
  25.         <!--[if lte IE 8]> 
  26.           <link rel="stylesheet" href="~/Content/CSS/ace-ie.min.css" /> 
  27.         <![endif]--> 
  28.  
  29.         <!-- inline styles related to this page --> 
  30.  
  31.         <!-- ace settings handler --> 
  32.  
  33.         <script src="~/Content/Js/ace-extra.min.js"></script> 
  34.         <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> 
  35.         <!--[if lt IE 9]> 
  36.         <script src="~/Content/Js/html5shiv.js"></script> 
  37.         <script src="~/Content/Js/respond.min.js"></script> 
  38.         <![endif]--> 
  39.    
  40. </head> 
  41. <body> 
  42.        
  43.    <div class="navbar navbar-default" id="navbar"> 
  44.             <script type="text/javascript"> 
  45.                 try { ace.settings.check('navbar', 'fixed') } catch (e) { }  
  46.             </script> 
  47.  
  48.             <div class="navbar-container" id="navbar-container"> 
  49.                 <div class="navbar-header pull-left"> 
  50.                     <a href="#" class="navbar-brand"> 
  51.                         <small> 
  52.                             <i class="icon-leaf"></i> 
  53.                              XiaoNao Admin  
  54.                         </small> 
  55.                     </a><!-- /.brand --> 
  56.                 </div><!-- /.navbar-header --> 
  57.  
  58.                 <div class="navbar-header pull-right" role="navigation"> 
  59.                     <ul class="nav ace-nav"> 
  60.                         <li class="green"> 
  61.                             <a data-toggle="dropdown" class="dropdown-toggle" href="#"> 
  62.                                 <i class="icon-envelope icon-animated-vertical"></i> 
  63.                                 <span class="badge badge-success">5</span> 
  64.                             </a> 
  65.  
  66.                             <ul class="pull-right dropdown-navbar dropdown-menu dropdown-caret dropdown-close"> 
  67.                                 <li class="dropdown-header"> 
  68.                                     <i class="icon-envelope-alt"></i> 
  69. Messages  
  70.                                 </li> 
  71.  
  72.                                 <li> 
  73.                                     <a href="#">   
  74.                                         <img src="~/Content/avatars/avatar.png" class="msg-photo" alt="Alex's Avatar" /> 
  75.                                         <span class="msg-body"> 
  76.                                             <span class="msg-title"> 
  77.                                                 <span class="blue">Alex:</span> 
  78.                                                 Ciao sociis natoque penatibus et auctor ...  
  79.                                             </span> 
  80.  
  81.                                             <span class="msg-time"> 
  82.                                                 <i class="icon-time"></i> 
  83.                                                 <span>a moment ago</span> 
  84.                                             </span> 
  85.                                         </span> 
  86.                                     </a> 
  87.                                 </li> 
  88.  
  89.                                 <li> 
  90.                                     <a href="#"> 
  91.                                         <img src="~/Content/avatars/avatar3.png" class="msg-photo" alt="Susan's Avatar" /> 
  92.                                         <span class="msg-body"> 
  93.                                             <span class="msg-title"> 
  94.                                                 <span class="blue">Susan:</span> 
  95.                                                 Vestibulum id ligula porta felis euismod ...  
  96.                                             </span> 
  97.  
  98.                                             <span class="msg-time"> 
  99.                                                 <i class="icon-time"></i> 
  100.                                                 <span>20 minutes ago</span> 
  101.                                             </span> 
  102.                                         </span> 
  103.                                     </a> 
  104.                                 </li> 
  105.  
  106.                                 <li> 
  107.                                     <a href="#"> 
  108.                                         <img src="~/Content/avatars/avatar4.png" class="msg-photo" alt="Bob's Avatar" /> 
  109.                                         <span class="msg-body"> 
  110.                                             <span class="msg-title"> 
  111.                                                 <span class="blue">Bob:</span> 
  112.                                                 Nullam quis risus eget urna mollis ornare ...  
  113.                                             </span> 
  114.  
  115.                                             <span class="msg-time"> 
  116.                                                 <i class="icon-time"></i> 
  117.                                                 <span>3:15 pm</span> 
  118.                                             </span> 
  119.                                         </span> 
  120.                                     </a> 
  121.                                 </li> 
  122.  
  123.                                 <li> 
  124.                                     <a href="#"> 
  125.                                         See all messages  
  126.                                         <i class="icon-arrow-right"></i> 
  127.                                     </a> 
  128.                                 </li> 
  129.                             </ul> 
  130.                         </li> 
  131.  
  132.                         <li class="light-blue"> 
  133.                             <a data-toggle="dropdown" href="#" class="dropdown-toggle"> 
  134.                                 <img class="nav-user-photo" src="~/Content/avatars/user.jpg" alt="Jason's Photo" /> 
  135.                                 <span class="user-info"> 
  136.                                     @if( Session["uname"]!=null){  
  137.                                     <small>Welcome,</small> 
  138.                                      @Session["uname"].ToString();  
  139.                                     }  
  140.                                 </span> 
  141.  
  142.                                 <i class="icon-caret-down"></i> 
  143.                             </a> 
  144.  
  145.                             <ul class="user-menu pull-right dropdown-menu dropdown-yellow dropdown-caret dropdown-close"> 
  146.                                 <li> 
  147.                                     <a href="#"> 
  148.                                         <i class="icon-cog"></i> 
  149.                                         Settings  
  150.                                     </a> 
  151.                                 </li> 
  152.                                 <li> 
  153.                                     <a href="#"> 
  154.                                         <i class="icon-user"></i> 
  155.                                         Profile  
  156.                                     </a> 
  157.                                 </li> 
  158.  
  159.                                 <li class="divider"></li> 
  160.  
  161.                                 <li> 
  162.                                     <a href="@Url.Action("LogOff","User")"> 
  163.                                         <i class="icon-off"></i> 
  164.                                         Logout  
  165.                                     </a> 
  166.                                 </li> 
  167.                             </ul> 
  168.                         </li> 
  169.                     </ul><!-- /.ace-nav --> 
  170.                 </div><!-- /.navbar-header --> 
  171.             </div><!-- /.container --> 
  172.         </div> 
  173.  
  174.         <div class="main-container" id="main-container"> 
  175.             <script type="text/javascript"> 
  176.                 try { ace.settings.check('main-container', 'fixed') } catch (e) { }  
  177.             </script> 
  178.  
  179.             <div class="main-container-inner"> 
  180.                 <a class="menu-toggler" id="menu-toggler" href="#"> 
  181.                     <span class="menu-text"></span> 
  182.                 </a> 
  183.  
  184.                 <div class="sidebar" id="sidebar"> 
  185.                     <script type="text/javascript"> 
  186.                         try { ace.settings.check('sidebar', 'fixed') } catch (e) { }  
  187.                     </script> 
  188.  
  189.                     <div class="sidebar-shortcuts" id="sidebar-shortcuts"> 
  190.                         <div class="sidebar-shortcuts-large" id="sidebar-shortcuts-large"> 
  191.                             <button class="btn btn-success"> 
  192.                                 <i class="icon-signal"></i> 
  193.                             </button> 
  194.  
  195.                             <button class="btn btn-info"> 
  196.                                 <i class="icon-pencil"></i> 
  197.                             </button> 
  198.  
  199.                             <button class="btn btn-warning"> 
  200.                                 <i class="icon-group"></i> 
  201.                             </button> 
  202.  
  203.                             <button class="btn btn-danger"> 
  204.                                 <i class="icon-cogs"></i> 
  205.                             </button> 
  206.                         </div> 
  207.  
  208.                         <div class="sidebar-shortcuts-mini" id="sidebar-shortcuts-mini"> 
  209.                             <span class="btn btn-success"></span> 
  210.  
  211.                             <span class="btn btn-info"></span> 
  212.  
  213.                             <span class="btn btn-warning"></span> 
  214.  
  215.                             <span class="btn btn-danger"></span> 
  216.                         </div> 
  217.                     </div> 
  218.                       
  219.                     <!-- #sidebar-shortcuts --> 
  220.  
  221.                     <ul class="nav nav-list"> 
  222.                         <li class="active"> 
  223.                             <a href="@Url.Action("Index","Admin")"> 
  224.                                 <i class="icon-dashboard"></i> 
  225.                                 <span class="menu-text"> 控制台 </span> 
  226.                             </a> 
  227.                         </li> 
  228.  
  229.                         <li> 
  230.                             <a href="#" class="dropdown-toggle"> 
  231.                                 <i class="icon-list"></i> 
  232.                                 <span class="menu-text"> 产品 </span> 
  233.  
  234.                                 <b class="arrow icon-angle-down"></b> 
  235.                             </a> 
  236.  
  237.                             <ul class="submenu"> 
  238.                                 <li> 
  239.                                     <a href="@Url.Action("Index","Product")"> 
  240.                                         <i class="icon-double-angle-right"></i> 
  241.                                          产品管理  
  242.                                     </a> 
  243.                                 </li> 
  244.  
  245.                                 <li> 
  246.                                     <a href="@Url.Action("CategoryList","Product")"> 
  247.                                         <i class="icon-double-angle-right"></i> 
  248.                                         分类管理  
  249.                                     </a> 
  250.                                 </li> 
  251.                             </ul> 
  252.                         </li> 
  253.                           
  254.                             <li> 
  255.                             <a href="#" class="dropdown-toggle"> 
  256.                                 <i class="icon-desktop"></i> 
  257.                                 <span class="menu-text"> 用户 </span> 
  258.  
  259.                                 <b class="arrow icon-angle-down"></b> 
  260.                             </a> 
  261.  
  262.                             <ul class="submenu"> 
  263.                                 <li> 
  264.                                     <a href="@Url.Action("Index","User")"> 
  265.                                         <i class="icon-double-angle-right"></i> 
  266.                                         用户管理  
  267.                                     </a> 
  268.                                 </li> 
  269.                                 <li> 
  270.                                     <a href="@Url.Action("EditInfo","User")"> 
  271.                                         <i class="icon-double-angle-right"></i> 
  272.                                         个人设置  
  273.                                     </a> 
  274.                                 </li> 
  275.                             </ul> 
  276.                         </li> 
  277.                    
  278.                     </ul><!-- /.nav-list --> 
  279.  
  280.                     <div class="sidebar-collapse" id="sidebar-collapse"> 
  281.                         <i class="icon-double-angle-left" data-icon1="icon-double-angle-left" data-icon2="icon-double-angle-right"></i> 
  282.                     </div> 
  283.  
  284.                     <script type="text/javascript"> 
  285.                         try { ace.settings.check('sidebar', 'collapsed') } catch (e) { }  
  286.                     </script> 
  287.                 </div> 
  288.  
  289.                 <div class="main-content"> 
  290.                     <div class="breadcrumbs" id="breadcrumbs"> 
  291.                         <script type="text/javascript"> 
  292.                             try { ace.settings.check('breadcrumbs', 'fixed') } catch (e) { }  
  293.                         </script> 
  294.  
  295.                         <ul class="breadcrumb"> 
  296.                             <li> 
  297.                                 <i class="icon-home home-icon"></i> 
  298.                                 <a href="@Url.Action("Index","Admin")">Home</a> 
  299.                             </li> 
  300.                             <li id="currentpart" class="active">控制台</li> 
  301.                         </ul><!-- .breadcrumb --> 
  302.  
  303.                         <div class="nav-search" id="nav-search"> 
  304.                             <form class="form-search"> 
  305.                                 <span class="input-icon"> 
  306.                                     <input type="text" placeholder="Search ..." class="nav-search-input" id="nav-search-input" autocomplete="off" /> 
  307.                                     <i class="icon-search nav-search-icon"></i> 
  308.                                 </span> 
  309.                             </form> 
  310.                         </div><!-- #nav-search --> 
  311.                     </div> 
  312.  
  313.                     <div class="page-content"> 
  314.                         <div class="page-header"> 
  315.                             <h1> 
  316.                                 <span>控制台</span> 
  317.                                 <small> 
  318.                                     <i class="icon-double-angle-right"></i> 
  319.                                     <span>查看</span> 
  320.                                 </small> 
  321.                             </h1> 
  322.                         </div><!-- /.page-header --> 
  323.  
  324.                         <div class="row"> 
  325.                             <div class="col-xs-12"> 
  326.                                 <!-- PAGE CONTENT BEGINS --> 
  327.                                  @RenderBody()  
  328.                                 <!-- PAGE CONTENT ENDS --> 
  329.                             </div><!-- /.col --> 
  330.                         </div><!-- /.row --> 
  331.                     </div><!-- /.page-content --> 
  332.                 </div><!-- /.main-content --> 
  333.  
  334.                 <div class="ace-settings-container" id="ace-settings-container"> 
  335.                     <div class="btn btn-app btn-xs btn-warning ace-settings-btn" id="ace-settings-btn"> 
  336.                         <i class="icon-cog bigger-150"></i> 
  337.                     </div> 
  338.  
  339.                     <div class="ace-settings-box" id="ace-settings-box"> 
  340.                         <div> 
  341.                             <div class="pull-left"> 
  342.                                 <select id="skin-colorpicker" class="hide"> 
  343.                                     <option data-skin="default" value="#438EB9">#438EB9</option> 
  344.                                     <option data-skin="skin-1" value="#222A2D">#222A2D</option> 
  345.                                     <option data-skin="skin-2" value="#C6487E">#C6487E</option> 
  346.                                     <option data-skin="skin-3" value="#D0D0D0">#D0D0D0</option> 
  347.                                 </select> 
  348.                             </div> 
  349.                             <span>&nbsp; Choose Skin</span> 
  350.                         </div> 
  351.  
  352.                         <div> 
  353.                             <input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-navbar" /> 
  354.                             <label class="lbl" for="ace-settings-navbar"> Fixed Navbar</label> 
  355.                         </div> 
  356.  
  357.                         <div> 
  358.                             <input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-sidebar" /> 
  359.                             <label class="lbl" for="ace-settings-sidebar"> Fixed Sidebar</label> 
  360.                         </div> 
  361.  
  362.                         <div> 
  363.                             <input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-breadcrumbs" /> 
  364.                             <label class="lbl" for="ace-settings-breadcrumbs"> Fixed Breadcrumbs</label> 
  365.                         </div> 
  366.  
  367.                         <div> 
  368.                             <input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-rtl" /> 
  369.                             <label class="lbl" for="ace-settings-rtl"> Right To Left (rtl)</label> 
  370.                         </div> 
  371.  
  372.                         <div> 
  373.                             <input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-add-container" /> 
  374.                             <label class="lbl" for="ace-settings-add-container"> 
  375.                                 Inside  
  376.                                 <b>.container</b> 
  377.                             </label> 
  378.                         </div> 
  379.                     </div> 
  380.                 </div><!-- /#ace-settings-container --> 
  381.             </div><!-- /.main-container-inner --> 
  382.  
  383.             <a href="#" id="btn-scroll-up" class="btn-scroll-up btn btn-sm btn-inverse"> 
  384.                 <i class="icon-double-angle-up icon-only bigger-110"></i> 
  385.             </a> 
  386.         </div><!-- /.main-container --> 
  387.  
  388.         <!-- basic scripts --> 
  389.  
  390.         <!--[if !IE]> 
  391.  
  392.         <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
  393.  
  394.         <![endif]-->    
  395.  
  396.         <!--[if IE]> 
  397. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
  398. <![endif]--> 
  399.  
  400.         <!--[if IE]> 
  401. <script type="text/javascript"> 
  402.  window.jQuery || document.write("<script src='~/Content/Js/jquery-1.10.2.min.js'>"+"<"+"/script>");  
  403. </script> 
  404. <![endif]--> 
  405.  
  406.         <script type="text/javascript"> 
  407.             if ("ontouchend" in document) document.write("<script src='~/Content/Js/jquery.mobile.custom.min.js'>" + "<" + "/script>");  
  408.         </script> 
  409.         <script src="~/Content/Js/bootstrap.min.js"></script> 
  410.         <script src="~/Content/Js/typeahead-bs2.min.js"></script> 
  411.  
  412.         <!-- page specific plugin scripts --> 
  413.  
  414.         <script src="~/Content/Js/jquery-ui-1.10.3.custom.min.js"></script> 
  415.         <script src="~/Content/Js/jquery.ui.touch-punch.min.js"></script> 
  416.         <script src="~/Content/Js/bootbox.min.js"></script> 
  417.  
  418.         <!-- ace scripts --> 
  419.  
  420.         <script src="~/Content/Js/ace-elements.min.js"></script> 
  421.         <script src="~/Content/Js/ace.min.js"></script> 
  422.  
  423.         <!-- inline scripts related to this page --> 
  424.  
  425.         <script type="text/javascript"> 
  426.             jQuery(function ($) {  
  427.  
  428.                 /* initialize the external events  
  429.                     -----------------------------------------------------------------*/  
  430.  
  431.                 $('#external-events div.external-event').each(function () {  
  432.  
  433.                     // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)  
  434.                     // it doesn't need to have a start or end  
  435.                     var eventObject = {  
  436.                         title: $.trim($(this).text()) // use the element's text as the event title  
  437.                     };  
  438.  
  439.                     // store the Event Object in the DOM element so we can get to it later  
  440.                     $(this).data('eventObject', eventObject);  
  441.  
  442.                     // make the event draggable using jQuery UI  
  443.                     $(this).draggable({  
  444.                         zIndex: 999,  
  445.                         revert: true,      // will cause the event to go back to its  
  446.                         revertDuration: 0  //  original position after the drag  
  447.                     });  
  448.  
  449.                 });  
  450.  
  451.                 /* initialize the calendar  
  452.                 -----------------------------------------------------------------*/  
  453.             })  
  454.         </script> 
  455.     <div style="display:none"><script src='http://v7.cnzz.com/stat.php?id=155540&web_id=155540' language='JavaScript' charset='gb2312'></script></div> 
  456.     <script src="~/Content/Js/niqiu.js"></script> 
  457.      @RenderSection("scripts", required: false)  
  458.    
  459. </body></html> 

#p#

二、引入Jqgrid

如果你的表格比较多,建议你做一个分部试图,重复利用,我的partview JqgridInit.cshtml 如下,

  1. <link rel="stylesheet" href="~/Content/CSS/ui.jqgrid.css" /> 
  2. <script src="~/Content/Js/jqGrid/jquery.jqGrid.min.js"></script> 
  3. <script src="~/Content/Js/jqGrid/i18n/grid.locale-en.js"></script> 
  4. <style> 
  5.     #pager2 {  
  6.         height: 40px;  
  7.     }  
  8.  
  9.     .FormGrid ,#DelTb1_list2{  
  10.         position: relative;  
  11.         overflow: visible;  
  12.         float: left;  
  13.     }  
  14.    .ui-jqgrid-sortable {  
  15.        height: 30px !important;          
  16.    }   
  17. </style> 
  18. <table id="list"></table> 
  19. <div id="pager"></div> 
  20. <span class="errorinfo"></span> 

list用来呈现数据,pager用来分页,errorinfo用来提示错误。jqgrid,涉及的配置比较多。需要后台代码的全面的支持,所以在介绍配置之前,先介绍下模型和仓库。

1.Product: 我们需要呈现的一个是一个产品,有很多不同的价格及其他,这些都将成为表格的列名。

  1. public class Product  
  2.     {  
  3.         /// <summary>  
  4.         /// Gets or sets the id.  
  5.         /// </summary>  
  6.         /// <value>The id.</value>  
  7.         [Key]  
  8.         public int ProductId { getset; }  
  9.  
  10.         /// <summary>  
  11.         /// 直接做型号处理  
  12.         /// </summary>  
  13.         public string ProductName { getset; }  
  14.         /// <summary>  
  15.         /// Gets or sets the category.  
  16.         /// </summary>  
  17.         /// <value>The category.</value>  
  18.         public string Category { getset; }  
  19.  
  20.         /// <summary>  
  21.         /// Gets or sets the brand.  
  22.         /// </summary>  
  23.         /// <value>The brand.</value>  
  24.         public string Brand { getset; }  
  25.  
  26.         public string Size { getset; }  
  27.  
  28.         /// <summary>  
  29.         /// Gets or sets the 规格.  
  30.         /// </summary>  
  31.         /// <value>The standard.</value>  
  32.         public string Standard { getset; }  
  33.  
  34.         /// <summary>  
  35.         /// 专柜  
  36.         /// </summary>  
  37.         public decimal ZhuanGui { getset; }  
  38.  
  39.         /// <summary>  
  40.         /// Gets or sets the 莎莎 price.  
  41.         /// </summary>  
  42.         /// <value>The sa sa price.</value>  
  43.         public decimal SaSaPrice { getset; }  
  44.  
  45.         /// <summary>  
  46.         /// Gets or sets the 卓越 price.  
  47.         /// </summary>  
  48.         /// <value>The zhuoyue price.</value>  
  49.         public decimal ZhuoyuePrice { getset; }  
  50.         /// <summary>  
  51.         /// Gets or sets the 卡莱美 price.  
  52.         /// </summary>  
  53.         /// <value>The ka lai price.</value>  
  54.         public decimal KaLaiPrice { getset; }  
  55.  
  56.         /// <summary>  
  57.         /// 雅施  
  58.         /// </summary>  
  59.         public decimal YaShi { getset; }  
  60.  
  61.         /// <summary>  
  62.         /// Gets or sets the 万宁 price.  
  63.         /// </summary>  
  64.         /// <value>The wanning price.</value>  
  65.         public decimal WanningPrice { getset; }  
  66.         /// <summary>  
  67.         /// Gets or sets the 屈臣氏 price.  
  68.         /// </summary>  
  69.         /// <value>The quchengshi price.</value>  
  70.         public decimal QuchengshiPrice { getset; }  
  71.         /// <summary>  
  72.         /// Gets or sets the 药店 price.  
  73.         /// </summary>  
  74.         /// <value>The drugstore price.</value>  
  75.         public decimal DrugstorePrice { getset; }  
  76.  
  77.         /// <summary>  
  78.         /// Gets or sets the others.  
  79.         /// </summary>  
  80.         /// <value>The others.</value>  
  81.         public string Others { getset; }  
  82.  
  83.         /// <summary>  
  84.         /// Gets or sets the create time.  
  85.         /// </summary>  
  86.         /// <value>The create time.</value>  
  87.         public DateTime CreateTime { getset; }  
  88.  
  89.         public string ImgUrl { getset; }  
  90.  
  91.         public Product()  
  92.         {  
  93.             CreateTime = DateTime.Now;  
  94.         }  
  95.     } 

2.ProductRepository (仓库真的很好,独立了业务逻辑,可测试,复用快),add、remove、update不用讲了,主要讲一讲排序。

1)排序查询的意义在于根据不同的属性进行排序。

  1. public class ProductRepository:IProductRepository  
  2.     {  
  3.         private readonly XNDb _db = new XNDb();  
  4.         //....  
  5.         public IEnumerable<Product> Find(string sort = "asc", string property = "ProductName"int skip = 0, int take = 10)  
  6.         {  
  7.             var propertyInfo = typeof(Product).GetProperty(property);//反射出这个属性  
  8.             Func<Product, object> expn = e => propertyInfo.GetValue(e, null);//委托  
  9.             var rawpros = _db.Products;  
  10.             IEnumerable<Product> pros = sort == "asc" ? rawpros.OrderBy(expn).Skip(skip).Take(take).ToArray()  
  11.                 : rawpros.OrderByDescending(expn).Skip(skip).Take(take).ToArray();//分页排序  
  12.             return pros;  
  13.         }  
  14.         //....  

在只考虑排序的情况下,控制器的代码就相对简单:

  1. public JsonResult GetAllPros( string sord = "asc"string sidx = "ProductName",int page = 1,  int rows = 10)  
  2.         {  
  3.             var pros = _repository.Find(sord, switchSidx(sidx), (page - 1) * rows, rows);  
  4.             var objpros = new List<object>(pros);  
  5.             var jsonData = JqGridModel.GridData(page, rows, _repository.Count, objpros);  
  6.             return Json(jsonData, JsonRequestBehavior.AllowGet);  
  7.         } 

如果涉及到复杂些的查询,等于不等于,包含之类的,会多了后面mark部分的参数,这里我用很笨的办法实现了单列查询,也就就是根据包含、等于、不等于先查出来,再排序,如果是多重查询,大家可以参考博客:http://www.codeproject.com/Articles/58357/Using-jqGrid-s-search-toolbar-with-multiple-filter

  1. public JsonResult GetAllPros( string sord = "asc"string sidx = "ProductName",int page = 1,   
  2.             int rows = 10, bool _search = false,string searchField=""string searchOper=""string searchString="")  
  3.         {  
  4.  
  5.             var rawpros = GetRawPros(_search, searchField, searchOper, searchString);  
  6.             var propertyInfo = typeof(Product).GetProperty(switchSidx(sidx));  
  7.             Func<Product, object> expn = e => propertyInfo.GetValue(e, null);  
  8.  
  9.             var enumerable = rawpros as Product[] ?? rawpros.ToArray();  
  10.             IEnumerable<Product> pros = sord == "asc" ? enumerable.OrderBy(expn).Skip((page - 1) * rows).Take(rows).ToArray()  
  11.                 : enumerable.OrderByDescending(expn).Skip((page - 1) * rows).Take(rows).ToArray();  
  12.  
  13.             var objpros = new List<object>(pros);  
  14.             var jsonData = JqGridModel.GridData(page, rows, enumerable.Count(), objpros);  
  15.             return Json(jsonData, JsonRequestBehavior.AllowGet);  
  16.         } 

需要说明的是,这里的switchsidx就是将中文列名转为对象属性名,一堆case语句,然后JqgridModel的getdata,是jqgrid定义好的一种json格式,包含了每页行数和总页数等信息,因为前段的每页行数是可以变化的。

  1. public class JqGridModel  
  2.     {  
  3.         /// <summary>  
  4.         /// Grids the data.  
  5.         /// </summary>  
  6.         /// <param name="page1">当前页数.</param>  
  7.         /// <param name="rows">每页显示数目.</param>  
  8.         /// <param name="total"></param>  
  9.         /// <param name="objects">集合对象</param>  
  10.         /// <returns>System.Object.</returns>  
  11.         public static object GridData(int page1, int rows, int total, IEnumerable<object> objects)  
  12.         {  
  13.             int pageSize = rows;  
  14.             var totalPages = (int)Math.Ceiling((float)total / pageSize);  
  15.  
  16.             //可根据具体情况,实现排序。  
  17.             var jsonData = new 
  18.             {  
  19.                 total = totalPages,  
  20.                 page = page1,  
  21.                 records = total,  
  22.                 rows = objects.ToArray()  
  23.             };  
  24.  
  25.             return jsonData;  
  26.         }  
  27.  
  28.     } 

2)需要一个新增:(记住返回json的时候要allowGet,不然可能造成添加失败,其他地方同理)

  1. [HttpPost]  
  2.         public ActionResult Create(Product product)  
  3.         {  
  4.             _repository.Add(product);  
  5.             var fu = _repository.FindByName(product.ProductName);  
  6.             return Json(fu, JsonRequestBehavior.AllowGet);  
  7.         } 

3)编辑和删除:这里的编辑有三个参数,一个对象,一个操作,一个id,id是个鸡肋,居然返回的是table的行号(会随着排序变化),oper可能是add,del,这里我只用到了edit,del传回的id尝试改变它为对象的id,但没成功。用了因外一种方式实现删除。

  1. [HttpPost]  
  2.         public ActionResult Edit(Product pro, string oper, int id)  
  3.         {  
  4.             if (oper == "edit")  
  5.             {  
  6.                 _repository.Update(pro);  
  7.                 pro.CreateTime = DateTime.Now;  
  8.             }  
  9.             return Json(pro, JsonRequestBehavior.AllowGet);  
  10.         }  
  11.  
  12.        [HttpPost]  
  13.        public ActionResult Delete(int id)  
  14.        {  
  15.         _repository.Remove(id);  
  16.          return Json(id, JsonRequestBehavior.AllowGet); ;  
  17.          } 

有了这四个方法就ok了。下面来讲配置。先打个预防针,主要关心两个方法,一个设置table,一个设置分页。然后代码比较长..... 希望没有打消你驾驭它的渴望。

全部控制器代码:包含了分类的一些,道理一样

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Linq.Expressions;  
  5. using System.Text;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8. using XNManage.Common;  
  9. using XNManage.Models;  
  10. using XNManage.Repository;  
  11. using XNManage.ViewModel;  
  12.  
  13. namespace XNManage.Controllers  
  14. {  
  15.     public class ProductController : Controller  
  16.     {  
  17.         //  
  18.         // GET: /Product/  
  19.         private readonly IProductRepository _repository;  
  20.  
  21.         private IEnumerable<CategoryViewModel> _categoryViewModels = new List<CategoryViewModel>();   
  22.  
  23.  
  24.         public ProductController(IProductRepository repository)  
  25.         {  
  26.             _repository = repository;  
  27.         }  
  28.  
  29.         #region 产品  
  30.  
  31.         [LoginValid]  
  32.         public ActionResult Index()  
  33.         {  
  34.             //CategoryInit();  
  35.             //ProductsInits();  
  36.             return View();  
  37.         }  
  38.  
  39.  
  40.         public JsonResult GetAllPros( string sord = "asc"string sidx = "ProductName",int page = 1,   
  41.             int rows = 10, bool _search = false,string searchField=""string searchOper=""string searchString="")  
  42.         {  
  43.  
  44.             var rawpros = GetRawPros(_search, searchField, searchOper, searchString);  
  45.             var propertyInfo = typeof(Product).GetProperty(switchSidx(sidx));  
  46.             Func<Product, object> expn = e => propertyInfo.GetValue(e, null);  
  47.  
  48.             var enumerable = rawpros as Product[] ?? rawpros.ToArray();  
  49.             IEnumerable<Product> pros = sord == "asc" ? enumerable.OrderBy(expn).Skip((page - 1) * rows).Take(rows).ToArray()  
  50.                 : enumerable.OrderByDescending(expn).Skip((page - 1) * rows).Take(rows).ToArray();  
  51.  
  52.             var objpros = new List<object>(pros);  
  53.             var jsonData = JqGridModel.GridData(page, rows, enumerable.Count(), objpros);  
  54.             return Json(jsonData, JsonRequestBehavior.AllowGet);  
  55.         }  
  56.  
  57.         private IEnumerable<Product> GetRawPros(bool search = falsestring searchField = ""string searchOper = ""string searchString = "")  
  58.         {  
  59.             var rawpros = _repository.FindAll();  
  60.             if (!search) return rawpros;  
  61.  
  62.             switch (switchSidx(searchField))  
  63.             {  
  64.                 case "ProductName":  
  65.                     switch (searchOper)  
  66.                     {  
  67.                         case "cn":  
  68.                             rawpros = rawpros.Where(n => n.ProductName.Contains(searchString));  
  69.                             break;  
  70.                         case "eq":  
  71.                             rawpros = rawpros.Where(n => n.ProductName == searchString);  
  72.                             break;  
  73.                         case "ne":  
  74.                             rawpros = rawpros.Where(n => n.ProductName != searchString);  
  75.                             break;  
  76.                         default:  
  77.                             rawpros = rawpros.Where(n => n.ProductName.Contains(searchString));  
  78.                             break;  
  79.                     }  
  80.                     break;  
  81.  
  82.                 case "Category":  
  83.                     switch (searchOper)  
  84.                     {  
  85.                         case "cn":  
  86.                             rawpros = rawpros.Where(n => n.Category.Contains(searchString));  
  87.                             break;  
  88.                         case "eq":  
  89.                             rawpros = rawpros.Where(n => n.Category == searchString);  
  90.                             break;  
  91.                         case "ne":  
  92.                             rawpros = rawpros.Where(n => n.Category != searchString);  
  93.                             break;  
  94.                         default:  
  95.                             rawpros = rawpros.Where(n => n.Category.Contains(searchString));  
  96.                             break;  
  97.                     }  
  98.                     break;  
  99.                 case "Brand":  
  100.                     switch (searchOper)  
  101.                     {  
  102.                         case "cn":  
  103.                             rawpros = rawpros.Where(n => n.Brand.Contains(searchString));  
  104.                             break;  
  105.                         case "eq":  
  106.                             rawpros = rawpros.Where(n => n.Brand == searchString);  
  107.                             break;  
  108.                         case "ne":  
  109.                             rawpros = rawpros.Where(n => n.Brand != searchString);  
  110.                             break;  
  111.                         default:  
  112.                             rawpros = rawpros.Where(n => n.Brand.Contains(searchString));  
  113.                             break;  
  114.                     }  
  115.                     break;  
  116.                 case "SaSaPrice":  
  117.                     switch (searchOper)  
  118.                     {  
  119.                         case "cn":  
  120.                             rawpros = rawpros.Where(n => n.SaSaPrice >= Convert.ToDecimal(searchString));  
  121.                             break;  
  122.                         case "eq":  
  123.                             rawpros = rawpros.Where(n => n.SaSaPrice == Convert.ToDecimal(searchString));  
  124.                             break;  
  125.                         case "ne":  
  126.                             rawpros = rawpros.Where(n => n.SaSaPrice != Convert.ToDecimal(searchString));  
  127.                             break;  
  128.                     }  
  129.                     break;  
  130.                 case "ZhuanGui":  
  131.                     switch (searchOper)  
  132.                     {  
  133.                         case "cn":  
  134.                             rawpros = rawpros.Where(n => n.ZhuanGui >= Convert.ToDecimal(searchString));  
  135.                             break;  
  136.                         case "eq":  
  137.                             rawpros = rawpros.Where(n => n.ZhuanGui == Convert.ToDecimal(searchString));  
  138.                             break;  
  139.                         case "ne":  
  140.                             rawpros = rawpros.Where(n => n.ZhuanGui != Convert.ToDecimal(searchString));  
  141.                             break;  
  142.                     }  
  143.                     break;  
  144.                 case "YaShi":  
  145.                     switch (searchOper)  
  146.                     {  
  147.                         case "cn":  
  148.                             rawpros = rawpros.Where(n => n.YaShi >= Convert.ToDecimal(searchString));  
  149.                             break;  
  150.                         case "eq":  
  151.                             rawpros = rawpros.Where(n => n.YaShi == Convert.ToDecimal(searchString));  
  152.                             break;  
  153.                         case "ne":  
  154.                             rawpros = rawpros.Where(n => n.YaShi != Convert.ToDecimal(searchString));  
  155.                             break;  
  156.                     }  
  157.                     break;  
  158.                 case "ZhuoyuePrice":  
  159.                     switch (searchOper)  
  160.                     {  
  161.                         case "cn":  
  162.                             rawpros = rawpros.Where(n => n.ZhuoyuePrice >= Convert.ToDecimal(searchString));  
  163.                             break;  
  164.                         case "eq":  
  165.                             rawpros = rawpros.Where(n => n.ZhuoyuePrice == Convert.ToDecimal(searchString));  
  166.                             break;  
  167.                         case "ne":  
  168.                             rawpros = rawpros.Where(n => n.ZhuoyuePrice != Convert.ToDecimal(searchString));  
  169.                             break;  
  170.                     }  
  171.                     break;  
  172.                 case "WanningPrice":  
  173.                     switch (searchOper)  
  174.                     {  
  175.                         case "cn":  
  176.                             rawpros = rawpros.Where(n => n.WanningPrice >= Convert.ToDecimal(searchString));  
  177.                             break;  
  178.                         case "eq":  
  179.                             rawpros = rawpros.Where(n => n.WanningPrice == Convert.ToDecimal(searchString));  
  180.                             break;  
  181.                         case "ne":  
  182.                             rawpros = rawpros.Where(n => n.WanningPrice != Convert.ToDecimal(searchString));  
  183.                             break;  
  184.                     }  
  185.                     break;  
  186.                 case "QuchengshiPrice":  
  187.                     switch (searchOper)  
  188.                     {  
  189.                         case "cn":  
  190.                             rawpros = rawpros.Where(n => n.QuchengshiPrice >= Convert.ToDecimal(searchString));  
  191.                             break;  
  192.                         case "eq":  
  193.                             rawpros = rawpros.Where(n => n.QuchengshiPrice == Convert.ToDecimal(searchString));  
  194.                             break;  
  195.                         case "ne":  
  196.                             rawpros = rawpros.Where(n => n.QuchengshiPrice != Convert.ToDecimal(searchString));  
  197.                             break;  
  198.                     }  
  199.                     break;  
  200.                 case "DrugstorePrice":  
  201.                     switch (searchOper)  
  202.                     {  
  203.                         case "cn":  
  204.                             rawpros = rawpros.Where(n => n.DrugstorePrice >= Convert.ToDecimal(searchString));  
  205.                             break;  
  206.                         case "eq":  
  207.                             rawpros = rawpros.Where(n => n.DrugstorePrice == Convert.ToDecimal(searchString));  
  208.                             break;  
  209.                         case "ne":  
  210.                             rawpros = rawpros.Where(n => n.DrugstorePrice != Convert.ToDecimal(searchString));  
  211.                             break;  
  212.                     }  
  213.                     break;  
  214.                 case "Others":  
  215.                     switch (searchOper)  
  216.                     {  
  217.                         case "cn":  
  218.                             rawpros = rawpros.Where(n => n.Others.Contains(searchString));  
  219.                             break;  
  220.                         case "eq":  
  221.                             rawpros = rawpros.Where(n => n.Others ==searchString);  
  222.                             break;  
  223.                         case "ne":  
  224.                             rawpros = rawpros.Where(n => n.Others !=searchString);  
  225.                             break;  
  226.                     }  
  227.                     break;  
  228.                 case "KaLaiPrice":  
  229.                     switch (searchOper)  
  230.                     {  
  231.                         case "cn":  
  232.                             rawpros = rawpros.Where(n => n.KaLaiPrice >= Convert.ToDecimal(searchString));  
  233.                             break;  
  234.                         case "eq":  
  235.                             rawpros = rawpros.Where(n => n.KaLaiPrice == Convert.ToDecimal(searchString));  
  236.                             break;  
  237.                         case "ne":  
  238.                             rawpros = rawpros.Where(n => n.KaLaiPrice != Convert.ToDecimal(searchString));  
  239.                             break;  
  240.                     }  
  241.                     break;  
  242.  
  243.                 default:  
  244.                     break;  
  245.             }  
  246.  
  247.             return rawpros;  
  248.         }   
  249.  
  250.  
  251.         /*  
  252.         public JsonResult GetData(GridSettings grid)  
  253.         {  
  254.  
  255.             var query = _repository.FindAll();  
  256.  
  257.             //filtring  
  258.             if (grid.IsSearch)  
  259.             {  
  260.                 //And  
  261.                 if (grid.Where.groupOp == "AND")  
  262.                     foreach (var rule in grid.Where.rules)  
  263.                         query = query.Where<Product>(  
  264.                             rule.field, rule.data,  
  265.                             (WhereOperation)StringEnum.Parse(typeof(WhereOperation), rule.op));  
  266.                 else  
  267.                 {  
  268.                     //Or  
  269.                     var temp = (new List<Product>()).AsQueryable();  
  270.                     foreach (var rule in grid.Where.rules)  
  271.                     {  
  272.                         var t = query.Where<Product>(  
  273.                         rule.field, rule.data,  
  274.                         (WhereOperation)StringEnum.Parse(typeof(WhereOperation), rule.op));  
  275.                         temp = temp.Concat<Product>(t);  
  276.                     }  
  277.                     //remove repeating records  
  278.                     query = temp.Distinct<Product>();  
  279.                 }  
  280.             }  
  281.  
  282.             //sorting  
  283.             query = query.OrderBy<Product>(grid.SortColumn,  
  284.                 grid.SortOrder);  
  285.  
  286.             //count  
  287.             var count = query.Count();  
  288.  
  289.             //paging  
  290.             var data = query.Skip((grid.PageIndex - 1) * grid.PageSize).Take(grid.PageSize).ToArray();  
  291.  
  292.             //converting in grid format  
  293.             var result = new  
  294.             {  
  295.                 total = (int)Math.Ceiling((double)count / grid.PageSize),  
  296.                 page = grid.PageIndex,  
  297.                 records = count,  
  298.                 rows = data.ToArray()  
  299.             };  
  300.  
  301.             //convert to JSON and return to client  
  302.             return Json(result, JsonRequestBehavior.AllowGet);  
  303.  
  304.         }  
  305.         */ 
  306.  
  307.  
  308.         //这个函数其实不必要!index中可以写英文。列名和index没有关系  
  309.         private string switchSidx(string sidx)  
  310.         {  
  311.             switch (sidx)  
  312.             {  
  313.                 case "型号":  
  314.                     return "ProductName";  
  315.                 case "类别":  
  316.                     return "Category";  
  317.                 case "品牌":  
  318.                     return "Brand";  
  319.                 case "规格":  
  320.                     return "Standard";  
  321.                 case "专柜":  
  322.                     return "ZhuanGui";  
  323.                 case "莎莎":  
  324.                     return "SaSaPrice";  
  325.                 case "雅施":  
  326.                     return "YaShi";  
  327.                 case "卓越":  
  328.                     return "ZhuoyuePrice";  
  329.                 case "卡莱美":  
  330.                     return "KaLaiPrice";  
  331.                 case "万宁":  
  332.                     return "WanningPrice";  
  333.                 case "屈臣氏":  
  334.                     return "QuchengshiPrice";  
  335.                 case "药店":  
  336.                     return "DrugstorePrice";  
  337.                 case "其他":  
  338.                     return "Others";  
  339.                 case "描述":  
  340.                     return "Description";  
  341.                 case "更新时间":  
  342.                     return "CreateTime";  
  343.                 default:  
  344.                     return "ProductName";  
  345.             }  
  346.         }  
  347.  
  348.         public string CategorySelectList()  
  349.         {  
  350.             var cs = _repository.AllCategories();  
  351.             var sb=new StringBuilder("<select>");  
  352.  
  353.             foreach (var category in cs)  
  354.             {  
  355.                 sb.Append(string.Format("<option value='{0}' >{1}</option>", category.CategoryName, category.CategoryName));  
  356.             }  
  357.             sb.Append("</select>");  
  358.             return sb.ToString();  
  359.         }  
  360.  
  361.         [HttpPost]  
  362.         public ActionResult Edit(Product pro, string oper, int id)  
  363.         {  
  364.             if (oper == "edit")  
  365.             {  
  366.                 _repository.Update(pro);  
  367.                 pro.CreateTime = DateTime.Now;  
  368.             }  
  369.             return Json(pro, JsonRequestBehavior.AllowGet);  
  370.         }  
  371.  
  372.         //  
  373.         // POST: /Product/Create  
  374.  
  375.         [HttpPost]  
  376.         public ActionResult Create(Product product)  
  377.         {  
  378.             _repository.Add(product);  
  379.             var fu = _repository.FindByName(product.ProductName);  
  380.             return Json(fu, JsonRequestBehavior.AllowGet);  
  381.         }  
  382.  
  383.        
  384.          
  385.         //  
  386.         // POST: /Product/Delete/5  
  387.  
  388.         [HttpPost]  
  389.         public ActionResult Delete(int id)  
  390.         {  
  391.             _repository.Remove(id);  
  392.             return Json(id);  
  393.         }  
  394.  
  395.         private void CategoryInit()  
  396.         {  
  397.             if (!_repository.AllCategories().Any())  
  398.             {  
  399.                 _repository.AddCategorie(new Category  
  400.                 {  
  401.                     CategoryName = "护肤品",  
  402.                     Description = "春天女生护肤专用" 
  403.                 });  
  404.                 _repository.AddCategorie(new Category()  
  405.                 {  
  406.                     CategoryName = "防晒",  
  407.                     Description = "夏日喷雾防晒" 
  408.                 }  
  409.                );  
  410.             }  
  411.         }  
  412.         private void ProductsInits()  
  413.         {  
  414.             if (!_repository.FindAll().Any())  
  415.             {  
  416.                 _repository.Add(new Product()  
  417.                 {  
  418.                     ProductName = "水宝宝",  
  419.                     Others = "防晒",  
  420.                     SaSaPrice = 78,  
  421.                     DrugstorePrice = 98  
  422.                 });  
  423.             }  
  424.         }  
  425.         #endregion   
  426.  
  427.         #region 分类  
  428.  
  429.         private IEnumerable<CategoryViewModel> initCategoryViewModels()  
  430.         {  
  431.             if (!_categoryViewModels.Any())  
  432.             {  
  433.                 var cas = _repository.AllCategories();  
  434.                 _categoryViewModels = cas.Select(n => new CategoryViewModel()  
  435.                 {  
  436.                     CategoryId = n.CategoryId,  
  437.                     CategoryName = n.CategoryName,  
  438.                     Description = n.Description,  
  439.                     ProductCount = _repository.GetCategorieProducts(n.CategoryName).Count()  
  440.                 });  
  441.             }  
  442.             return _categoryViewModels;  
  443.         }  
  444.         public JsonResult GetAllCategorys(string sord = "asc"string sidx = "CategoryName"int page = 1, int rows = 10)  
  445.         {  
  446.             IList<object> pros = new List<object>(FindCategoryViewModels(sord, sidx, (page - 1) * rows, rows));  
  447.             var jsonData = JqGridModel.GridData(page, rows, initCategoryViewModels().Count(), pros);  
  448.             return Json(jsonData, JsonRequestBehavior.AllowGet);  
  449.         }  
  450.  
  451.           
  452.  
  453.         public IEnumerable<CategoryViewModel> FindCategoryViewModels(string sort = "asc",  
  454.             string property = "CategoryName"int skip = 0, int take = 10)  
  455.         {  
  456.             var propertyInfo = typeof(CategoryViewModel).GetProperty(property);  
  457.             Func<CategoryViewModel, object> expn = e => propertyInfo.GetValue(e, null);  
  458.             var fakeProfiles =initCategoryViewModels();  
  459.             IEnumerable<CategoryViewModel> pros = sort == "asc" ? fakeProfiles.OrderBy(expn).Skip(skip).Take(take).ToArray()  
  460.                 : fakeProfiles.OrderByDescending(expn).Skip(skip).Take(take).ToArray();  
  461.             return pros;  
  462.         }  
  463.  
  464.         public ActionResult EditCategory(CategoryViewModel model,string oper, int id)  
  465.         {  
  466.             if (oper == "edit")  
  467.             {  
  468.                 var ca = new Category()  
  469.                 {  
  470.                     CategoryId = model.CategoryId,  
  471.                     CategoryName = model.CategoryName,  
  472.                     Description = model.Description,  
  473.                 };  
  474.                 _repository.UpdateCategorie(ca);  
  475.             }  
  476.             return Json(model, JsonRequestBehavior.AllowGet);  
  477.         }  
  478.  
  479.         public ActionResult CategoryList()  
  480.         {  
  481.             return View();  
  482.         }  
  483.  
  484.         [HttpPost]  
  485.         public ActionResult CreateCategory(Category category)  
  486.         {  
  487.             _repository.AddCategorie(category);  
  488.             var fu = _repository.FindCategorieById(category.CategoryId);  
  489.  
  490.             var cm = new CategoryViewModel()  
  491.             {  
  492.                 CategoryName = fu.CategoryName,  
  493.                 CategoryId = fu.CategoryId,  
  494.                 Description = fu.Description,  
  495.                 ProductCount = _repository.GetCategorieProducts(fu.CategoryName).Count()  
  496.             };  
  497.  
  498.             return Json(cm, JsonRequestBehavior.AllowGet);  
  499.         }  
  500.  
  501.         public ActionResult DeletCategory(int id)  
  502.         {  
  503.             _repository.RemoveCategorie(id);  
  504.             return Json(1);  
  505.         }  
  506.  
  507.         public PartialViewResult JqgridInit()  
  508.         {  
  509.  
  510.             return PartialView();  
  511.         }  
  512.  
  513.         public JsonResult GetChartData()  
  514.         {  
  515.             var cms = initCategoryViewModels().ToList();  
  516.             var count =_repository.Count;  
  517.             var chartDatas = cms.Select(n => new ChartData  
  518.             {  
  519.                 label = n.CategoryName,  
  520.                 data =  Math.Round((double)n.ProductCount / count, 3),  
  521.             }).ToArray();  
  522.             return Json(chartDatas, JsonRequestBehavior.AllowGet);  
  523.         }  
  524.  
  525.         #endregion   
  526.  
  527.     }  

#p#

1)table的设置

  1. jQuery("#list").jqGrid({  
  2.         url: '/Product/GetAllPros'//获取数据源  
  3.         datatype: "json",  
  4.         colNames: ['操作''ProductId''类别''品牌''型号''规格''专柜''莎莎''卓越''卡莱美''雅施''万宁''屈臣氏''药店''其他''更新时间'], //定义列名   
  5.         colModel: [ //name 是对应我们的Product模型的属性,Index可以为中文也可以为英文,不必于上面colnames对应,顺序对就行了。查询的时候传到后台的是index。  
  6.             {  
  7.                 name: 'myac', index: '操作', width: 60, fixed: true, sortable: false, resize: false, formatter: 'actions', formatoptions: {  
  8.                     keys: true,   
  9.                     delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback, },  
  10.                 }                  
  11.             },  
  12.            //详细的字段配置信息请见博客:http://www.cnblogs.com/huozhicheng/archive/2012/11/20/2778649.html   
  13.            { name: 'ProductId', index: 'ProductId', hidden: true, editable: true },  
  14.            { name: 'Category', index: '类别', editable: true, edittype: 'select', editoptions: { dataUrl: "/Product/CategorySelectList" }, searchoptions: { sopt: ['eq''ne''cn'] } },  
  15.            { name: 'Brand', index: '品牌', editable: true, editrules: { required: false }, searchoptions: { sopt: ['eq''ne''cn'] } },  
  16.            { name: 'ProductName', index: '型号', editable: true, editrules: { required: true }, searchoptions: { sopt: ['eq''ne''cn'] } },  
  17.            { name: 'Standard', index: '规格', editable: true, edittype: 'textarea', searchoptions: { sopt: ['eq''ne''cn'] } },  
  18.            { name: 'ZhuanGui', index: '专柜', editable: true, width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },//formatter: 'integer',  formatter: 'integer',   
  19.            { name: 'SaSaPrice', index: '莎莎', editable: true,width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  20.             { name: 'ZhuoyuePrice', index: '卓越', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  21.             { name: 'KaLaiPrice', index: '卡莱美', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  22.             { name: 'YaShi', index: '雅施', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  23.             { name: 'WanningPrice', index: '万宁', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  24.             { name: 'QuchengshiPrice', index: '屈臣氏', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  25.             { name: 'DrugstorePrice', index: '药店', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  26.             { name: 'Others', index: '其他', editable: true, edittype: 'textarea', searchoptions: { sopt: ['eq''ne''cn'] } },  
  27.             {  
  28.                 name: 'CreateTime', index: '更新时间', width: 200, formatter: 'date'//时间格式显示  
  29.                 formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s', searchoptions: { sopt: ['eq''ne''cn'] } }  
  30.             }  
  31.         ],  
  32.         rowNum: 10,  
  33.         rowList: [10, 20, 30],  
  34.         sortorder: "asc",  
  35.         pager: '#pager2',  
  36.         sortname: 'ProductName',  
  37.         viewrecords: true,  
  38.         caption: "产品明细",  
  39.         autowidth: true,  
  40.         multiselect: true,  
  41.         height: 180,  
  42.         gridComplete: function () {  
  43.             var icons = $(".ui-icon-trash");//隐藏删除键  
  44.             icons.hide();//我隐藏了删除键 因为id的问题  
  45.             //var ids = jQuery("#list2").jqGrid('getDataIDs');  
  46.             //for (var i = 0; i < ids.length; i++) {  
  47.             //    be = "<span class='ui-icon ui-icon-pencil'></span>";//修改  
  48.             //    se = "<span class='ui-icon ui-icon-trash'></span>";//删除  
  49.             //    ce = "<span class='icon-ok  ui-icon'></span>";//删除  
  50.             //    jQuery("#list2").jqGrid('setRowData', ids[i], { act: be + se + ce });  
  51.             //}  
  52.              //这个部分是可以添加定义的按钮,自己用脚本去实现。  
  53.  
  54.         },  
  55.         loadComplete: function () {  
  56.             $("#grid-table").hide();  
  57.             var table = this;  
  58.             enableTooltips(table);  
  59.             updatePagerIcons(table);  
  60.         },  
  61.  
  62.         editurl: "/Product/Edit"//编辑的地址 操作栏触发的操作都会丢到这个action中响应。 add edit del  
  63.         //改变传id的方法无效!!!!  
  64.         serializeDelData: function (postdata) {  
  65.             var rowdata = jQuery('#list2').getRowData(postdata.id);  
  66.             return { id: postdata.id, oper: postdata.oper, user: rowdata };  
  67.         }  
  68.         //edit  del  
  69.     }); 

形成样子如下:

[[115287]]

colModel涉及的配置较多,不同的字段有不同的呈现,可以参考博客 http://www.cnblogs.com/huozhicheng/archive/2012/11/20/2778649.html

2)pager 用来形成分页和集成一些操作。

  1. jQuery("#list").jqGrid('navGrid''#pager2', {  
  2.              //调整ui 也就是我们看到的: ,但这个删除图标是我代码加上去的。  
  3.             edit: true,  
  4.             editicon: 'icon-pencil blue',  
  5.             add: true,  
  6.             addicon: 'icon-plus-sign purple',  
  7.             del: false,  
  8.             delicon: 'icon-trash red',  
  9.             search: true,  
  10.             searchicon: 'icon-search orange',  
  11.             refresh: true,  
  12.             refreshicon: 'icon-refresh green',  
  13.             view: false,  
  14.             viewicon: 'icon-zoom-in grey',  
  15.         },  
  16.         {  
  17.             //eidt  
  18.             url: '/Product/Edit', mtype: 'POST',  
  19.             afterSubmit: function (xhr, postdata) {  
  20.                 var id = $("#list2").jqGrid('getGridParam''selrow');  
  21.                 jQuery("#list2").jqGrid('setRowData', id, postdata);  
  22.             }, closeAfterEdit: true, closeOnEscape: true 
  23.         },  
  24.         {  
  25.             //add  
  26.             recreateForm: true,  
  27.             url: '/Product/Create',  
  28.             mtype: 'POST',  
  29.             afterSubmit: function (xhr, postdata) {  
  30.                 var id = $("#list2").jqGrid('getGridParam''selrow');  
  31.                 jQuery("#list2").jqGrid('addRowData', postdata.Id, postdata);  
  32.                 return [true'successfule!'false];  
  33.             }, closeAfterAdd: true 
  34.         },  
  35.         {  
  36.             //delete 此处无效  
  37.             recreateForm: true,  
  38.             url: '/Product/Delete', mtype: 'POST',  
  39.             beforeShowForm: function (e) {  
  40.                 var form = $(e[0]);  
  41.                 if (form.data('styled')) return false;  
  42.                 form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');  
  43.                 styleDeleteForm(form);  
  44.                 form.data('styled'true); return true;  
  45.             },  
  46.             afterSubmit: function (xhr, postdata) {  
  47.                 var consoleDlg = $("#list2");  
  48.                 var selectedRowIds =  
  49.                     $("#list2").jqGrid("getGridParam""selarrrow");  
  50.                 var len = selectedRowIds.length;  
  51.                 for (var i = 0; i < len ; i++) {  
  52.                     $("#list2").jqGrid("delRowData", selectedRowIds[0]);  
  53.                 }  
  54.             },  
  55.  
  56.             closeAfterDel: true 
  57.  
  58.         },  
  59.         {  
  60.             //search  
  61.             recreateForm: true,  
  62.             afterShowSearch: function(e){  
  63.                 var form = $(e[0]);  
  64.                 form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')  
  65.                 styleSearchForm(form);  
  66.             },  
  67.             afterRedraw: function(){  
  68.                 styleSearchFilters($(this));  
  69.             }  
  70.                         ,  
  71.            // multipleSearch: true,  
  72.             closeAfterSearch: true 
  73.  
  74.          },  
  75.         {  
  76.             //view       
  77.  
  78.             }  
  79.     ); 

在下面加入按钮的方法以及执行删除:jquery2.0中的绑定写法有些不同,也就是on的用法。

  1. function updatePagerIcons() {  
  2.  //...  
  3.   var x = $("#pager2_left").find("#coco");  
  4.         if (x.length == 0) {  
  5.             $("#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'>" +  
  6.                 "<span class='ui-icon icon-trash blue'></span></div></td>");  
  7.         }  
  8.  
  9. }  
  10.  //绑定事件 执行删除   
  11.     $("#pager2_left table tbody>tr").on("click"'#coco', function () {  
  12.         var selectedRowIds = $("#list2").jqGrid("getGridParam""selarrrow");  
  13.         var len = selectedRowIds.length;  
  14.         if (len != 0) {  
  15.             if (confirm("确定要删除选中项?")) {  
  16.                 for (var i = 0; i < len; i++) {  
  17.                     var rowData = $("#list2").jqGrid('getRowData', selectedRowIds[i]);  
  18.                     $.post('/Product/Delete', { id: rowData.ProductId }, function (data) {  
  19.                         $("#list2").jqGrid("delRowData", selectedRowIds[0]);  
  20.                     });  
  21.                 }  
  22.             }  
  23.         } else {  
  24.             $.infoShow("未勾选", 0);  
  25.         }  
  26.     }); 

形成这个样子:

[[115288]]

全部前台代码:

  1. @{  
  2.     ViewBag.Title = "Index";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5. @Html.Partial("JqgridInit")  
  6. <script>  
  7.     $(function () {  
  8.     $(".page-header h1 span,#currentpart").html("产品");  
  9.     $(".page-header h1 small span").html("产品管理");  
  10.     $(".nav-list>li:eq(1)").addClass("active").siblings().removeClass("active");  
  11.       
  12.     jQuery("#list2").jqGrid({  
  13.         url: '/Product/GetAllPros',  
  14.         datatype: "json",  
  15.         colNames: ['操作''ProductId''类别''品牌''型号''规格''专柜''莎莎''卓越''卡莱美''雅施''万宁''屈臣氏''药店''其他''更新时间'],  
  16.         colModel: [  
  17.             {  
  18.                 name: 'myac', index: '操作', width: 60, fixedtrue, sortable: false, resize: false, formatter: 'actions', formatoptions: {  
  19.                     keys: true,   
  20.                     delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback, },//改变原来的样式  msg: '您确定要删除这条记录?</span>  
  21.                     searchoptions: { sopt: ['eq''ne''cn'] },  
  22.                 }  
  23.                 //    name: 'act', index: 'act', width: 75, sortable: false  
  24.             },  
  25.            { name: 'ProductId', index: 'ProductId', hidden: true, editable: true },  
  26.            { name: 'Category', index: '类别', editable: true, edittype: 'select', editoptions: { dataUrl: "/Product/CategorySelectList" }, searchoptions: { sopt: ['eq''ne''cn'] } },  
  27.            { name: 'Brand', index: '品牌', editable: true, editrules: { required: false }, searchoptions: { sopt: ['eq''ne''cn'] } },  
  28.            { name: 'ProductName', index: '型号', editable: true, editrules: { required: true }, searchoptions: { sopt: ['eq''ne''cn'] } },  
  29.            { name: 'Standard', index: '规格', editable: true, edittype: 'textarea', searchoptions: { sopt: ['eq''ne''cn'] } },  
  30.            { name: 'ZhuanGui', index: '专柜', editable: true, width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },//formatter: 'integer',  formatter: 'integer',   
  31.            { name: 'SaSaPrice', index: '莎莎', editable: true,width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  32.             { name: 'ZhuoyuePrice', index: '卓越', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  33.             { name: 'KaLaiPrice', index: '卡莱美', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  34.             { name: 'YaShi', index: '雅施', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  35.             { name: 'WanningPrice', index: '万宁', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  36.             { name: 'QuchengshiPrice', index: '屈臣氏', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  37.             { name: 'DrugstorePrice', index: '药店', editable: true, formatter: 'integer', width: 60, searchoptions: { sopt: ['eq''ne''cn'] } },  
  38.             { name: 'Others', index: '其他', editable: true, edittype: 'textarea', searchoptions: { sopt: ['eq''ne''cn'] } },  
  39.             {  
  40.                 name: 'CreateTime', index: '更新时间', width: 200, formatter: 'date',  
  41.                 formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s', searchoptions: { sopt: ['eq''ne''cn'] } }  
  42.             }  
  43.         ],  
  44.         rowNum: 10,  
  45.         rowList: [10, 20, 30],  
  46.         sortorder: "asc",  
  47.         pager: '#pager2',  
  48.         sortname: 'ProductName',  
  49.         viewrecords: true,  
  50.         caption: "产品明细",  
  51.         autowidth: true,  
  52.         multiselect: true,  
  53.         height: 180,  
  54.         gridComplete: function () {  
  55.             var icons = $(".ui-icon-trash");//隐藏删除键  
  56.             icons.hide();  
  57.             //var ids = jQuery("#list2").jqGrid('getDataIDs');  
  58.             //for (var i = 0; i < ids.length; i++) {  
  59.             //    be = "<span class='ui-icon ui-icon-pencil'></span>";//修改  
  60.             //    se = "<span class='ui-icon ui-icon-trash'></span>";//删除  
  61.             //    ce = "<span class='icon-ok  ui-icon'></span>";//删除  
  62.             //    jQuery("#list2").jqGrid('setRowData', ids[i], { act: be + se + ce });  
  63.             //}  
  64.         },  
  65.         loadComplete: function () {  
  66.             $("#grid-table").hide();  
  67.             var table = this;  
  68.             enableTooltips(table);  
  69.             updatePagerIcons(table);  
  70.         },  
  71.  
  72.         editurl: "/Product/Edit",  
  73.         //无效!!!!  
  74.         serializeDelData: function (postdata) {  
  75.             var rowdata = jQuery('#list2').getRowData(postdata.id);  
  76.             return { id: postdata.id, oper: postdata.oper, user: rowdata };  
  77.         }  
  78.         //edit  del  
  79.     });  
  80.     jQuery("#list2").jqGrid('navGrid''#pager2', {  
  81.             edit: true,  
  82.             editicon: 'icon-pencil blue',  
  83.             add: true,  
  84.             addicon: 'icon-plus-sign purple',  
  85.             del: false,  
  86.             delicon: 'icon-trash red',  
  87.             search: true,  
  88.             searchicon: 'icon-search orange',  
  89.             refresh: true,  
  90.             refreshicon: 'icon-refresh green',  
  91.             view: false,  
  92.             viewicon: 'icon-zoom-in grey',  
  93.         },  
  94.         {  
  95.             //eidt  
  96.             url: '/Product/Edit', mtype: 'POST',  
  97.             afterSubmit: function (xhr, postdata) {  
  98.                 var id = $("#list2").jqGrid('getGridParam''selrow');  
  99.                 jQuery("#list2").jqGrid('setRowData', id, postdata);  
  100.             }, closeAfterEdit: true, closeOnEscape: true 
  101.         },  
  102.         {  
  103.             //add  
  104.             recreateForm: true,  
  105.             url: '/Product/Create',  
  106.             mtype: 'POST',  
  107.             afterSubmit: function (xhr, postdata) {  
  108.                 var id = $("#list2").jqGrid('getGridParam''selrow');  
  109.                 jQuery("#list2").jqGrid('addRowData', postdata.Id, postdata);  
  110.                 return [true'successfule!'false];  
  111.             }, closeAfterAdd: true 
  112.         },  
  113.         {  
  114.             //delete  
  115.             recreateForm: true,  
  116.             url: '/Product/Delete', mtype: 'POST',  
  117.             beforeShowForm: function (e) {  
  118.                 var form = $(e[0]);  
  119.                 if (form.data('styled')) return false;  
  120.                 form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');  
  121.                 styleDeleteForm(form);  
  122.                 form.data('styled'true); return true;  
  123.             },  
  124.             afterSubmit: function (xhr, postdata) {  
  125.                 var consoleDlg = $("#list2");  
  126.                 var selectedRowIds =  
  127.                     $("#list2").jqGrid("getGridParam""selarrrow");  
  128.                 var len = selectedRowIds.length;  
  129.                 for (var i = 0; i < len ; i++) {  
  130.                     $("#list2").jqGrid("delRowData", selectedRowIds[0]);  
  131.                 }  
  132.             },  
  133.  
  134.             closeAfterDel: true 
  135.  
  136.         },  
  137.         {  
  138.             //search  
  139.             recreateForm: true,  
  140.             afterShowSearch: function(e){  
  141.                 var form = $(e[0]);  
  142.                 form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')  
  143.                 styleSearchForm(form);  
  144.             },  
  145.             afterRedraw: function(){  
  146.                 styleSearchFilters($(this));  
  147.             }  
  148.                         ,  
  149.            // multipleSearch: true,  
  150.             closeAfterSearch: true 
  151.  
  152.          },  
  153.         {  
  154.             //view       
  155.  
  156.             }  
  157.     );  
  158.     //添加注释  
  159.     function enableTooltips(table) {  
  160.         $('.navtable .ui-pg-button').tooltip({ container: 'body' });  
  161.         $(table).find('.ui-pg-div').tooltip({ container: 'body' });  
  162.     }  
  163.  
  164.  
  165.     function beforeDeleteCallback(e) {  
  166.         var form = $(e[0]);  
  167.         if (form.data('styled')) return false;  
  168.         form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');  
  169.         styleDeleteForm(form);  
  170.         form.data('styled'true);  
  171.         return true;  
  172.     }  
  173.  
  174.  
  175.     //修改 删除form的样式  
  176.     function styleDeleteForm(form) {  
  177.         var buttons = form.next().find('.EditButton .fm-button');  
  178.         buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon  
  179.         buttons.eq(0).addClass('btn-danger').prepend('<i class="icon-trash"></i>');  
  180.         buttons.eq(1).prepend('<i class="icon-remove"></i>');  
  181.     }  
  182.  
  183.     //更新分页图标  
  184.     function updatePagerIcons() {  
  185.  
  186.         var replacement =  
  187.         {  
  188.             'ui-icon-seek-first''icon-double-angle-left bigger-140',  
  189.             'ui-icon-seek-prev''icon-angle-left bigger-140',  
  190.             'ui-icon-seek-next''icon-angle-right bigger-140',  
  191.             'ui-icon-seek-end''icon-double-angle-right bigger-140' 
  192.         };  
  193.         $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {  
  194.             var icon = $(this);  
  195.             var $class = $.trim(icon.attr('class').replace('ui-icon'''));  
  196.  
  197.             if ($class in replacement) icon.attr('class''ui-icon ' + replacement[$class]);  
  198.         });  
  199.  
  200.         var x = $("#pager2_left").find("#coco");  
  201.         if (x.length == 0) {  
  202.             $("#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'>" +  
  203.                 "<span class='ui-icon icon-trash blue'></span></div></td>");  
  204.         }  
  205.     }  
  206.  
  207.     function styleSearchForm(form) {  
  208.         var dialog = form.closest('.ui-jqdialog');  
  209.         var buttons = dialog.find('.EditTable')  
  210.         buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class''icon-retweet');  
  211.         buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class''icon-comment-alt');  
  212.         buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class''icon-search');  
  213.     }  
  214.     function styleSearchFilters(form) {  
  215.         form.find('.delete-rule').val('X');  
  216.         form.find('.add-rule').addClass('btn btn-xs btn-primary');  
  217.         form.find('.add-group').addClass('btn btn-xs btn-success');  
  218.         form.find('.delete-group').addClass('btn btn-xs btn-danger');  
  219.     }  
  220.  
  221.     //绑定事件 执行删除  
  222.     $("#pager2_left table tbody>tr").on("click"'#coco', function () {  
  223.         var selectedRowIds = $("#list2").jqGrid("getGridParam""selarrrow");  
  224.         var len = selectedRowIds.length;  
  225.         if (len != 0) {  
  226.             if (confirm("确定要删除选中项?")) {  
  227.                 for (var i = 0; i < len; i++) {  
  228.                     var rowData = $("#list2").jqGrid('getRowData', selectedRowIds[i]);  
  229.                     $.post('/Product/Delete', { id: rowData.ProductId }, function (data) {  
  230.                         $("#list2").jqGrid("delRowData", selectedRowIds[0]);  
  231.                     });  
  232.                 }  
  233.             }  
  234.         } else {  
  235.             $.infoShow("未勾选", 0);  
  236.         }  
  237.     });  
  238.     });  
  239. </script> 

至此基本告成,还有些可以优化。

如果本文对你有帮助,请霸气的支持下    :)  tks~

需要源码的同学,请留邮箱。备注:数据库是EntityFramework + CE4.0,账户密码都是:admin

模板源码: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/


本文出自:http://www.cnblogs.com/stoneniqiu/p/3815028.html

责任编辑:林师授 来源: stoneniqiu的博客
相关推荐

2009-07-22 09:36:54

使用UpdataModASP.NET MVC

2009-07-23 15:44:39

ASP.NET MVC

2010-11-02 08:46:55

NupackASP.NET MVC

2010-04-09 09:28:37

View Model

2009-07-20 17:16:46

IIS中使用ASP.N

2010-06-23 15:44:03

ASP.NET MVC

2021-06-22 16:59:56

微软.NETC# 软件开发

2009-07-20 16:45:41

使用StringBuiASP.NET

2010-06-25 08:51:46

ASP.NET MVC

2014-07-29 10:00:30

ASP.NETMVCAutoFac

2009-07-31 12:43:59

ASP.NET MVC

2009-07-24 13:20:44

MVC框架ASP.NET

2010-11-18 08:46:27

ASP.NET MVC

2009-07-22 16:34:36

使用T4ASP.NET MVC

2009-05-05 14:02:14

PlaceHolder控件ASP.NET

2009-07-23 14:31:20

ASP.NET MVC

2009-07-20 10:53:59

ASP.NET MVC

2009-07-22 10:09:59

ASP.NET MVC

2009-07-22 13:24:24

ASP.NET MVC

2011-01-19 11:17:36

点赞
收藏

51CTO技术栈公众号