Build a JqGrid table containing the CRUD function in five minutes, crudjqgrid

Source: Internet
Author: User
Tags jqgrid

Build a JqGrid table containing the CRUD function in five minutes, crudjqgrid

JgGrid has also been used in previous projects to learn a little about its basic functions. There is an open-source project outside China on the Internet, but it is not suitable for my own style, therefore, it took more than three days to encapsulate JqGrid. This is also the first complete small example written in the past 10 months for developers. The experts just did not need to read it, however, due to the short time, there are still many shortcomings that need to be improved later.

The overall idea is a configuration class that is compatible with the chained programming style.SetIt is easy to recognize. Make a personal user manual after recording.

Chained programming style
@ (Html. jqGrid ("testJqGrid2", new GridConfiguration (ColumnFactory. create ("Name", "Name "). setWidth ("300 "). setEditable (ColumnEditType. textarea ). setSearchable (SearchFiledType. string) ColumnFactory. create ("Id", "Number "). setWidth ("300 "). setEditable (ColumnEditType. text ). setSearchable (SearchFiledType. int) ColumnFactory. create ("Skin", "Skin color "). setWidth ("300 "). setEditable (ColumnEditType. textarea), ColumnFactory. create (null, "operation "). setWidth ("100 "). setFormatter ("customerFmatter "))). setGroupHeaders (new GroupHeader ("Name", 2, "<font style = \" color: red; \ "> details </font> ")). setCaption ("JqGrid test "). setHeight ("250 "). setUrl ("/Home/GridData", new Dictionary <string, string >{{ "name", "halower "}}). setSortName ("Name "). setSortOrder (SortOrderType. desc ). setLoadText ("loading data, please wait... "). setBuiltInOperation (GridOperatorType. add | GridOperatorType. edit | GridOperatorType. delete | GridOperatorType. search ). setPager ("pageId2 "). setRowList (new [] {5, 15, 33,55 }). setSubGridModel (ColumnFactory. create ("Name", "Name "). setWidth ("150"), ColumnFactory. create ("Language", "Chinese "). setWidth ("150"), ColumnFactory. create ("Country", "nationality "). setWidth ("150 ")). setSubGridUrl ("/Home/SubGridData "). setSubGridPostParams (new [] {"Name "}). setEditUrl ("/Home/EditPerson "). setMultiselect ())
Configuration-based mashups
1 @ (Html. jqGrid ("testJqGrid", new GridConfiguration 2 {3 GridColumns = new List <GridColumn> 4 {5 ColumnFactory. create ("Id", "Number "). setWidth ("300 "). setEditable (ColumnEditType. text ). setSearchable (SearchFiledType. int), 6 new GridColumn {DisplayName = "Name", Field = "Name", Width = "300", Editable = true, Search = true }, 7 new GridColumn {DisplayName = "Skin color", Field = "Skin", Width = "300", Editable = true, Search = true, SearchFiledType = SearchFiledType. string}, 8 ColumnFactory. create (null, "operation "). setWidth ("100 "). setFormatter ("customerFmatter") 9}, 10 Caption = "JqGrid test", 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; \ "> details </font>") }}, 18 LoadText = "loading data, please wait... ", 19 RowList = new [] {11,15, 20}, 20 SubGridModel = new [] 21 {22 new SubGridTable 23 (24 ColumnFactory. create ("Name", "Name "). setWidth ("150"), 25 ColumnFactory. create ("Language", "Chinese "). setWidth ("150"), 26 ColumnFactory. create ("Country", "nationality "). 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)
The background Code enables you to sort, query, and manage all pages. You can also add, modify, and query local hosting of restricted formats.
// Master table 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 = "test" + (I + 1), Skin = "Yellow" + I });} // supports EF paging sorting // var context = new PersonContext (); // context. persons. pagination (this );
// Context. persons. pagination (this, p => p. id> 15 & p. id <100); return Content (list. pagination (this);} // subtable 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 = "Chinese" + I, Name = "sub-table test" + (I + 1 ), country = "China" + I});} return list. pushSubGrid (this);} // use the native Form to submit public JsonResult EditPerson (Person perso N, string id) {if (! ModelState. IsValidField ("Id ")&&! String. IsNullOrEmpty (id ))
// Batch Delete // 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);} // custom non-native commit public JsonResult AddInfo (int id) {return Json (id. delegateNotBuildInOperation (Bussiness. addInfo ));}

Adjust the following position and automatically adjust the column order, including the master table and sub-table.

The effect is as follows:

What JS code is required, what is generated, and others adopt the default configuration
<Script> $ (function () {function _ my97datePick (elem) {jQuery (elem ). datepicker ({dateFormat: 'yy-mm-dd'}) ;}; jQuery ("# testJqGrid2 "). jqGrid ({"url": "/Home/GridData", "datatype": "json", "colNames": ["no.", "name", "skin color ", "time", "operation"], "colModel": [{"name": "Id", "index": "Id", "width": "300 ", "align": "right", "sortable": true, "hidden": false, "editable": true, "search": true, "stype": "text ", "sorttype": "int", "edittype": "text", "searcho Ptions ": {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", "searchop Tions ": {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: 'select date'}, sopt: ['eq ', 'lt', 'gt '] }}, {"width": "120", "align": "right", "sortable": false, "hidden": false, "editable": false, "search": false, "formatter": customerFmatte R, "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; \ "> details </font>"}]}, "sortorder": "desc", "caption": "JqGrid test", "loadtext ": "loading data, please wait... "," pginput ": false," pos TData ": {" name ":" halower "," DisplayFileds ":" Id, Name, Skin, DateTime "," GridKey ":" Id "}," autowidth ": true, "autoencode": false, "height": "250", "multiselect": true, "editurl": "/Home/ChangePersonInfo", "subGrid": true, "subGridModel": [{"name": ["name", "Chinese", "nationality"], "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": "edit", "add": true, "addtext": "add ", "del": true, "deltext": "delete", "search": true, "searchtext": "search", "refresh": false, "RefreshText ": "refresh" },{ 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; \ "> details </font>"}]}) ;}</script>

Why use the chain style to take over the code?

1. The use of the chain style mainly takes into account the JQ style, while the code structure and relevance can be clear, while retaining the configuration class can also make yourself accustomed to the traditional style of people to configure their own

2. The background takes over the code. The main purpose is to keep the UI Layer simple and lightweight, and force the user to transfer the business to the service layer/business layer for processing, so as to prevent collaborators from engaging in a lot of business code in the Controller.

Table Interface Method description
Method Name Parameter type Function Description
SetGridKey String Set table ID Columns
SetPager String Enable pagination and set the paging Control Id
SetUrl String, Dictionary <string, string> Set the address for retrieving data from the master table.
SetCaption String Set table name
SetRowList Int [] Set the number of display drop-down records
SetSortName String Set the default sorting column. It can be a column name or a number. This parameter will be submitted to the background.
SetDirection DriectionType Set the writing direction in the table
SetSortOrder SortOrderType Set the initial sorting type when reading XML or JSON data from the server
SetLoadText String Set the text displayed during data request and sorting
SetPgInput Bool Set whether the navigation bar has a page number input box
SetAutoWidth Bool Set automatic width
SetAutoEencode Bool If this parameter is set to true, encodes is used to encode the data from the server and the submitted data. For example, <! [CDATA [<to be converted to <]>
SetDataType ResponseDataType Set the expected data type of the table.
SetEmptyRecords String Set the information displayed when the returned (or current) quantity is zero. This option is only valid when Setviewrecords is set to true.
SetHeight String Set the table height. Value, percentage, or auto
SetMultiselect Bool When this attribute is set to true, multi-row selection is enabled. check boxes are displayed.
SetSubGridUrl String Set the data request Url of a sub-table
SetSubGridPostParams String [] Set the parent table field that the sub-table depends on when obtaining data.
SetSubGridModel GridColumn [] Configure table columns
SetBuiltInOperation GridOperatorType Enable built-in operation types
SetGroupHeaders GroupHeader [] Set the header Group
SetEditUrl String Set the Add delete operation URL for built-in editing.
SetMultipleSearch Bool Set Advanced Search
Column Method Interface Description
Method Name Parameter type Function Description
SetWidth String Set the initial width of the column. pixels and percentage are available.
SetHidden Bool Specifies whether to hide columns during initialization.
SetEditable ColumnEditType Define whether the defined field can be edited
SetSearchable SearchFiledType Define search
SetSearchable SearchFiledType, ColumnSearchType Define search
SetSortable ColumnSortType Enable sorting
SetFieldName String, string Set field ing name
SetFormatter String Custom Formatter Functions
SetUnformat String Custom Unformat function. You need to obtain the original value during modification.
SetEditoptions String Set a series of Edit options
SetEitrules String Set edited rules
SetFrozen Bool Set freeze Columns

It is not clear about the parameters involved in custom multiple verification rules and options, so Eitrules will temporarily use string as the parameter for configuration later. Although very simple, but soon for the new year, if interested, I think it is still worth some physical strength, you can consider sponsoring me a red envelope, contact halower@foxmail.com

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.