五分钟搭建起一个包含CRUD功能的JqGrid表格
之前的项目也曾用过JgGrid对它的基本功能也是略有了解,网上有个国外的开源的项目,但是不适合个人的风格,所以花了3天空余的时间封装了下JqGrid,也算是参加开发工作10个月以来写的第一个比较完整的小例子,高手们就直接飘过不用看了,但是由于时间短,还有很多的不足,需要后期再完善。
整体思路就是一个配置类,同时兼容了链式编程的风格,所有的动作接口都以Set开头,便于识别。记录下来以后做个人的使用手册。
源码地址:https://github.com/halower/JqGridForMvc/
推荐写法:
链式编程风格
@(Html.JqGrid("testJqGrid2", new GridConfiguration ( ColumnFactory.Create("Name","姓名").SetWidth("300").SetEditable(ColumnEditType.Textarea).SetSearchable(SearchFiledType.String) ColumnFactory.Create("Id", "编号").SetWidth("300").SetEditable(ColumnEditType.Text).SetSearchable(SearchFiledType.Int) ColumnFactory.Create("Skin", "肤色").SetWidth("300").SetEditable(ColumnEditType.Textarea), ColumnFactory.Create(null, "操作").SetWidth("100").SetFormatter("customerFmatter") ) ) .SetGroupHeaders(new GroupHeader("Name", 2, "<font style=\"color:red;\">详细内容</font>")) .SetCaption("JqGrid测试").SetHeight("250") .SetUrl("/Home/GridData", new Dictionary<string, string> { { "name", "halower" } }) .SetSortName("Name").SetSortOrder(SortOrderType.Desc).SetLoadText("正在加载数据请骚等...") .SetBuiltInOperation(GridOperatorType.Add | GridOperatorType.Edit | GridOperatorType.Delete | GridOperatorType.Search) .SetPager("pageId2").SetRowList(new[] { 5, 15, 33,55 }) .SetSubGridModel( ColumnFactory.Create("Name", "姓名").SetWidth("150"), ColumnFactory.Create("Language", "中文").SetWidth("150"), ColumnFactory.Create("Country", "国籍").SetWidth("150") ) .SetSubGridUrl("/Home/SubGridData").SetSubGridPostParams(new[] { "Name" }) .SetEditUrl("/Home/EditPerson").SetMultiselect() )
配置类为主的混搭风格
1 @(Html.JqGrid("testJqGrid", new GridConfiguration 2 { 3 GridColumns = new List<GridColumn> 4 { 5 ColumnFactory.Create("Id", "编号").SetWidth("300").SetEditable(ColumnEditType.Text).SetSearchable(SearchFiledType.Int), 6 new GridColumn{DisplayName ="姓名",Field ="Name",Width ="300",Editable = true,Search =true}, 7 new GridColumn{DisplayName ="肤色",Field ="Skin",Width ="300",Editable = true,Search =true,SearchFiledType =SearchFiledType.String}, 8 ColumnFactory.Create(null, "操作").SetWidth("100").SetFormatter("customerFmatter") 9 }, 10 Caption = "JqGrid测试", 11 Height = "250", 12 PagerId = "pageId", 13 SortName ="Name", 14 Sortorder = SortOrderType.Desc.ToString().ToLower(), 15 GridOperation = new GridOperation { Add =true,Delete =true,Edit =true,Search =true}, 16 SetGroupHeaders=true, 17 ColSPanConfiguation=new ColSPanConfiguation{GroupHeaders =new[]{new GroupHeader("Name", 2, "<font style=\"color:red;\">详细内容</font>")}}, 18 LoadText = "正在加载数据请骚等...", 19 RowList =new []{11,15,20}, 20 SubGridModel = new[] 21 { 22 new SubGridTable 23 ( 24 ColumnFactory.Create("Name", "姓名").SetWidth("150"), 25 ColumnFactory.Create("Language", "中文").SetWidth("150"), 26 ColumnFactory.Create("Country", "国籍").SetWidth("150") 27 ) 28 }, 29 Multiselect = true, 30 EditUrl = "/Home/EditPerson" 31 }) 32 .SetUrl("/Home/GridData",null) 33 .SetSubGridUrl("/Home/SubGridData").SetSubGridPostParams(new[] { "Name" }) 34 )
强类型方式
@( g.JqGrid("testJqGrid").MainGrid( g.GridColumn(x => x.Id, 300), g.GridColumn(x => x.Name, 300), g.GridColumn(x => x.Skin, 300), g.GridColumn("操作", null, "customerFmatter")) .Caption("JqGrid测试").Height("250") .Url("/Home/GridData", new Dictionary<string, string> { { "name", "halower" } }) .SortName("Name").SortOrder(SortOrderType.Desc).LoadText("正在加载数据请骚等...") .Pager("pageId") .SubGrid( g.GridColumn(x=>x.Name,300), g.GridColumn(x=>x.Language,300), g.GridColumn(x=>x.Country,300) ) .SubGridUrl("/Home/SubGridData").SubGridPostParams(new[] { "Name" }) )
后台代码实现了排序,查询,分页的全部托管,对增改查也实现了格式限制型的局部托管。
//主表格 public ContentResult GridData(string name) { var list = new List<Person>(); for (var i = 0; i < 300000; i++) { list.Add(new Person { Id = i + 1, Name = "测试" + (i + 1), Skin = "Yellow" + i }); } //支持EF分页排序 //var context=new PersonContext(); //context.Persons.Pagination(this);
//context.Persons.Pagination(this,p=>p.id>15&&p.id<100); return Content(list.Pagination(this)); } //子表格 public string SubGridData(string name) { var list = new List<Chinese>(); for (var i = 0; i < 5; i++) { list.Add(new Chinese { Id = i + 1, Language = "中文" + i, Name = "子表测试" + (i + 1), Country = "中国" + i }); } return list.PushSubGrid(this); } //使用原生的Form提交 public JsonResult EditPerson(Person person, string id) { if (!ModelState.IsValidField("Id") && !string.IsNullOrEmpty(id))
//批量删除 //return Json(id.DelegateBuildInOperation(Bussiness.DeleteInfo, this)); return Json(id.DelegateNotBuildInOperation(Bussiness.DeleteInfo)); var optDic = new Dictionary<OperTypes, Func<Person, bool>> { {OperTypes.Add, Bussiness.AddPerson}, {OperTypes.Edit, Bussiness.EditPerson}, {OperTypes.Delete, Bussiness.DeletePerson} }; return Json(person.DelegateBuildInOperation(optDic, this)); } //自定义非原生提交 public JsonResult AddInfo(int id) { return Json(id.DelegateNotBuildInOperation(Bussiness.AddInfo)); }
调整下面的位置,自动进行列顺序【包含主表格和子表格】调整
效果如下:
需要什么JS代码,生成什么,其它采用默认配置
<script>$(function(){function _my97datePick(elem){jQuery(elem).datepicker({ dateFormat: 'yy-mm-dd' });};jQuery("#testJqGrid2").jqGrid({"url":"/Home/GridData","datatype":"json","colNames":["编号","姓名","肤色","时间","操作"],"colModel":[{"name":"Id","index":"Id","width":"300","align":"right","sortable":true,"hidden":false,"editable":true,"search":true,"stype":"text","sorttype":"int","edittype":"text","searchoptions":{sopt:['eq','lt','gt']}},{"name":"Name","index":"Name","width":"300","align":"right","sortable":true,"hidden":false,"editable":true,"search":true,"stype":"text","sorttype":"text","edittype":"textarea","searchoptions":{sopt:['eq','bw','cn']}},{"name":"Skin","index":"Skin","width":"300","align":"right","sortable":false,"hidden":false,"editable":true,"search":false,"edittype":"text","searchoptions":{sopt:['eq','bw','cn']}},{"name":"DateTime","index":"DateTime","width":"300","align":"right","sortable":false,"hidden":false,"editable":true,"search":true,"stype":"text","edittype":"text","searchoptions":{dataInit:_my97datePick,attr:{title:'选择日期'},sopt:['eq','lt','gt']}},{"width":"120","align":"right","sortable":false,"hidden":false,"editable":false,"search":false,"formatter":customerFmatter,"searchoptions":{sopt:['eq','bw','cn']}}],"rowNum":10,"rowList":[5,15,33,55],"pager":"#pageId2","sortname":"Name","mtype":"post","viewrecords":true,"ColSPanConfiguation":{"useColSpanStyle":true,"groupHeaders":[{"startColumnName":"Name","numberOfColumns":2,"titleText":"<font style=\"color:red;\">详细内容</font>"}]},"sortorder":"desc","caption":"JqGrid测试","loadtext":"正在加载数据请骚等...","pginput":false,"postData":{"name":"halower","DisplayFileds":"Id,Name,Skin,DateTime","GridKey":"Id"},"autowidth":true,"autoencode":false,"height":"250","multiselect":true,"editurl":"/Home/ChangePersonInfo","subGrid":true,"subGridModel":[{"name":["姓名","中文","国籍"],"width":["150","150","150"],"align":["right","right","right"],"params":["Name"]}],"subGridUrl":"/Home/SubGridData?DisplayFileds=Name,Language,Country","frozen":false});jQuery("#testJqGrid2").jqGrid('navGrid', '#pageId2',{"edit":true,"edittext":"编辑","add":true,"addtext":"添加","del":true,"deltext":"删除","search":true,"searchtext":"查找","refresh":false,"RefreshText":"刷新"},{checkOnSubmit:true,checkOnUpdate:true,closeAfterEdit:true,closeOnEscape:true},{checkOnSubmit:true, closeAfterAdd: true,recreateForm:true},{},{multipleSearch:true});jQuery("#testJqGrid2").jqGrid('setGroupHeaders',{"useColSpanStyle":true,"groupHeaders":[{"startColumnName":"Name","numberOfColumns":2,"titleText":"<font style=\"color:red;\">详细内容</font>"}]});})</script>
为什么要使用链式风格,使用接管代码?
1.采用链式风格主要考虑到JQ的风格,同时可以使代码结构和关联度清晰,同时保留配置类可以也让自己习惯传统风格的人自己配置
2.后台接管代码,主要目的是保持UI层的简洁,轻量级,强制使用者将业务转移到服务层/业务层去处理,防止合作者在Controller里搞一大堆业务代码。
表格接口方法说明
方法名称 | 参数类型 | 功能说明 |
SetGridKey | string | 设置表格标识列 |
SetPager | string | 设置启用分页,并设置分页控件Id |
SetUrl | string , Dictionary<string, string> | 设置获取主表数据的地址 |
SetCaption | string | 设置表格名称 |
SetRowList | int[] | 设置显示下拉记录数 |
SetSortName | string | 设置默认的排序列。可以是列名称或者是一个数字,这个参数会被提交到后台 |
SetDirection | DriectionType | 设置表格中的书写方向 |
SetSortOrder | SortOrderType | 设置 从服务器读取XML或JSON数据时初始的排序类型 |
SetLoadText | string | 设置数据请求和排序时显示的文本 |
SetPgInput | bool | 设置导航栏是否有页码输入框 |
SetAutoWidth | bool | 设置自动宽度 |
SetAutoEencode | bool | 设置为true时,对来自服务器的数据和提交数据进行encodes编码。如<![CDATA[<将被转换为<]]> |
SetDataType | ResponseDataType | 设置表格希望获得的数据的类型 |
SetEmptyRecords | string | 设置当返回(或当前)数量为零时显示的信息此项只用当Setviewrecords 设置为true时才有效。 |
SetHeight | string | 设置表格高度。可为数值、百分比或auto |
SetMultiselect | bool | 设置此属性设为true时启用多行选择,出现复选框 |
SetSubGridUrl | string | 设置子表数据请求Url |
SetSubGridPostParams | string[] | 设置子表获取数据时所依赖父表字段 |
SetSubGridModel | GridColumn[] | 设置子表格列配置 |
SetBuiltInOperation | GridOperatorType | 设置启用内置操作类型 |
SetGroupHeaders | GroupHeader[] | 设置表头分组 |
SetEditUrl | string | 设置内建编辑新增删除操作URL |
SetMultipleSearch | bool | 设置高级搜索 |
列方法接口说明
方法名称 | 参数类型 | 功能说明 |
SetWidth | string | 设置列的初始宽度,可用pixels和百分比 |
SetHidden | bool | 定义初始化时,列是否隐藏 |
SetEditable | ColumnEditType | 定义定义字段是否可编辑 |
SetSearchable | SearchFiledType | 定义搜索 |
SetSearchable | SearchFiledType ,ColumnSearchType | 定义搜索 |
SetSortable | ColumnSortType | 启用排序 |
SetFieldName | string, string | 设置字段映射名 |
SetFormatter | string | 自定义Formatter函数 |
SetUnformat | string | 自定义Unformat函数,在修改时需要获取原来的值 |
SetEditoptions | string | 设置编辑的一系列选项 |
SetEitrules | string | 设置编辑的一系列规则 |
SetFrozen | bool | 设置冻结列 |
其中对于自定义的多种验证等规则和选项涉及的参数,尚不是很清楚,Eitrules便暂时使用string作为参数在后面在做配置化处理。虽然很简单,不过快过年了,如果有感兴趣的,觉得还是费点体力的,可以联系halower@foxmail.com