복붙노트

[JQUERY] 다이나믹있는 jqGrid 컬럼 바인딩

JQUERY

다이나믹있는 jqGrid 컬럼 바인딩

해결법


  1. 1.document.ready이 시도 :

    document.ready이 시도 :

    $.ajax(
        {
           type: "POST",
           url: "SomeUrl/GetColumnsAndData",
           data: "",
           dataType: "json",
           success: function(result)
           {
                colD = result.colData;
                colN = result.colNames;
                colM = result.colModel;
    
                jQuery("#list").jqGrid({
                    jsonReader : {
                        cell: "",
                        id: "0"
                    },
                    url: 'SomeUrl/Getdata',
                    datatype: 'jsonstring',
                    mtype: 'POST',
                    datastr : colD,
                    colNames:colN,
                    colModel :colM,
                    pager: jQuery('#pager'),
                    rowNum: 5,
                    rowList: [5, 10, 20, 50],
                    viewrecords: true
                })
           },
           error: function(x, e)
           {
                alert(x.readyState + " "+ x.status +" "+ e.msg);   
           }
        });
    setTimeout(function() {$("#list").jqGrid('setGridParam',{datatype:'json'}); },50);
    

    나를 위해이 잘 작동.


  2. 2.내 솔루션 8 월 2015 테오 만 Shipahi의 훌륭한 답변으로 같은 생각의 일종이다.

    내 솔루션 8 월 2015 테오 만 Shipahi의 훌륭한 답변으로 같은 생각의 일종이다.

    나는 JSON 데이터의 집합을 반환하는 웹 서비스를 가지고 있지만, 실제 열은 시간이 지남에 따라 달라질 수 있습니다.

    내가하고 싶었던 것은 숨기기 내있는 jqGrid에서 JSON 컬럼의 일부를, 그리고이 특정 JSON 필드 (이 경우, SegmentName에서) 중요한 분야 중 하나 경우에 따라 열 몇 가지의 폭을 설정합니다.

    여기에 내가 무엇을 최대 온이다 :

    $(function () {
        //  Load the JSON data we'll need to populate our jqGrid
    
        // ID of a [Segment_Set] record in our database (which our web service will load the data for.
        var SegmentSetId = 12345;
    
        $.ajax(
        {
            type: "GET",
            url: "/Service1.svc/LoadSegmentAttributes/" + SegmentSetId,
            dataType: "json",
            success: function (JSONdata) {
                // 
                //  Work through our JSON data, and create the two arrays needed by jqGrid 
                //  to display this dynamic data.
                //
                var listOfColumnModels = [];
                var listOfColumnNames = [];
    
                for (var prop in JSONdata[0]) {
                    if (JSONdata[0].hasOwnProperty(prop)) {
                        //  We have found one property (field) in our JSON data.
                        //  Add a column to the list of Columns which we want our jqGrid to display
                        listOfColumnNames.push(prop);
    
                        //  How do we want this field to be displayed in our jqGrid ?
                        var bHidden = (prop == "SegmentID") || (prop == "SegmentSequenceInx");
                        var columnWidth = (prop == "SegmentName") ? 200 : 50;
    
                        listOfColumnModels.push({
                            name: prop,
                            width: columnWidth,
                            sortable: true,
                            hidden: bHidden
                        });
                    }
                }
    
                //  Now we have our JSON data, and list of Column Headings and Models, we can create our jqGrid.
                CreateJQGrid(JSONdata, listOfColumnModels, listOfColumnNames);
            }
        });
    });
    

    그리고 여기있는 jqGrid를 생성하는 기능입니다 :

    function CreateJQGrid(JSONdata, listOfColumnModels, listOfColumnNames) {
        //  After loading the JSON data from our webservice, and establishing the list of 
        //  Column Names & Models, we can call this function to create the jqGrid.
        $("#SegmentRulesGrid").jqGrid({
    
            datatype: "local",
            data: JSONdata,
            localReader: {
                id: "SegmentID",        //  The Primary Key field in our JSONdata 
                repeatitems: false
            },
            mtype: "GET",
            colNames: listOfColumnNames,
            colModel: listOfColumnModels,
            rowNum: 15,
            loadonce: true,
            gridview: true,
            autowidth: true,
            height: 350,
            pager: '#pager',
            rowList: [15, 30, 100, 300],
            rownumbers: true,
            viewrecords: true,
            caption: 'Segment Rules',
        });
    }
    

    도움이 되었기를 바랍니다.

    물론 내 솔루션에 하나의 단점은 한 번에 오히려 부하보다, 그리드에서 데이터의 한 페이지를 표시하기 전에 JSON의 모든 데이터를로드한다고 주장이다. 당신은 엄청난 양의 데이터가있는 경우 문제가 될 수 있습니다.


  3. 3.누군가가 MVC 다음 http://blog.lieberlieber.com/2010/07/07/asp-net-mvc-and-a-generic-jqquery-grid-jqtgrid/ 사용하여이 기능을 구현하고자하는 경우 더 좋은 솔루션입니다.

    누군가가 MVC 다음 http://blog.lieberlieber.com/2010/07/07/asp-net-mvc-and-a-generic-jqquery-grid-jqtgrid/ 사용하여이 기능을 구현하고자하는 경우 더 좋은 솔루션입니다.


  4. 4.이 그리드는 다시 가능한 열이 추가 될 때마다인가? 당신은 동적 열 모델을 사용하여 각 시간을 로컬로 데이터를 저장하고 단지 언로드 / 재 작성 그리드 수있다.

    이 그리드는 다시 가능한 열이 추가 될 때마다인가? 당신은 동적 열 모델을 사용하여 각 시간을 로컬로 데이터를 저장하고 단지 언로드 / 재 작성 그리드 수있다.

    또한 동적 / 숨기기 열을 보여주는 데모의 일부를보고 할 수 있습니다. 당신은 얼마나 많은 컬럼에 따라, 당신은 당신의 프로그램에서 동일한 개념을 사용할 수 있습니다.

    그 도움을합니까?


  5. 5.또 다른 해결책은;

    또 다른 해결책은;

     $("#datagrid").jqGrid({
            //url: "user.json",
            //datatype: "json",
            datatype: "local",
            data: dataArray,
            colNames:getColNames(dataArray[0]),
            colModel:getColModels(dataArray[0]),
            rowNum:100,
            loadonce: true,
            pager: '#navGrid',
            sortname: 'SongId',
            sortorder: "asc",
            height: "auto", //210,
            width:"auto",
            viewrecords: true,
            caption:"JQ GRID"
        });
    
        function getColNames(data) {
            var keys = [];
            for(var key in data) {
                if (data.hasOwnProperty(key)) {
                    keys.push(key);
                }
            }
    
            return keys;
        }
    
        function  getColModels(data) {
            var colNames= getColNames(data);
            var colModelsArray = [];
            for (var i = 0; i < colNames.length; i++) {
                var str;
                if (i === 0) {
                    str = {
                        name: colNames[i],
                        index:colNames[i],
                        key:true,
                        editable:true
                    };
                } else {
                    str = {
                        name: colNames[i],
                        index:colNames[i],
                        editable:true
                    };
                }
                colModelsArray.push(str);
            }
    
            return colModelsArray;
        }
    

  6. 6.

    function columnsData(Data) {
        var str = "[";
        for (var i = 0; i < Data.length; i++) {
            str = str + "{name:'" + Data[i] + "', index:'" + Data[i] + "', editable: true}";
            if (i != Data.length - 1) {
                str = str + ",";
            }
        }
        str = str + "]";
        return str;
    }
    

  7. 7.나는 모두 JSON으로 데이터 수익의 유형을 jsonstring 브루노에 의해 제안 솔루션을 시도했습니다, 그것은하지만 작동 옵션 datastr 경우 : COLD 존재 - 실행하지 않는 데이터에 대한 추가 요청, 필터 먼저 검색된 데이터에 대한 작업을 수행하지만 존재하지 않는 - 그리드로드의 데이터에 대한 이중 요청

    나는 모두 JSON으로 데이터 수익의 유형을 jsonstring 브루노에 의해 제안 솔루션을 시도했습니다, 그것은하지만 작동 옵션 datastr 경우 : COLD 존재 - 실행하지 않는 데이터에 대한 추가 요청, 필터 먼저 검색된 데이터에 대한 작업을 수행하지만 존재하지 않는 - 그리드로드의 데이터에 대한 이중 요청


  8. 8.나는 실행하는 것이 좋습니다 것입니다 $ ( "# 목록")있는 jqGrid ( 'setGridParam', {데이터 형식 : 'JSON'}).; 그리드의 loadComplete 이벤트에 -이 방법은 그리드는 확실히 존재합니다. 그래서 그냥 대신의 setTimeout (...)의 그리드 정의에 다음을 추가 :

    나는 실행하는 것이 좋습니다 것입니다 $ ( "# 목록")있는 jqGrid ( 'setGridParam', {데이터 형식 : 'JSON'}).; 그리드의 loadComplete 이벤트에 -이 방법은 그리드는 확실히 존재합니다. 그래서 그냥 대신의 setTimeout (...)의 그리드 정의에 다음을 추가 :

    loadComplete : function () {
        $ ("#list").jqGrid('setGridParam',{datatype:'json'});
    }
    

    나를 위해 일했다!


  9. 9.가져 오기 기능을 사용하여 그것을 할 경우, 당신은 여전히있는 jqGrid의 페이징 기능을 활용할 수 있습니다. "데이터"와 "그리드"로 구성으로 확인 "GetColumnsAndData"반환 정상 그리드 데이터를 확인 (또는 "jsonGrid"이러한 값을 변경).

    가져 오기 기능을 사용하여 그것을 할 경우, 당신은 여전히있는 jqGrid의 페이징 기능을 활용할 수 있습니다. "데이터"와 "그리드"로 구성으로 확인 "GetColumnsAndData"반환 정상 그리드 데이터를 확인 (또는 "jsonGrid"이러한 값을 변경).

    편집 : 또한 반환되는 "그리드"설정 확신 하나의 (a URL 값 만 데이터를 검색 할) "URL"되어 있는지 확인합니다.

    $('#grid').jqGridImport({
        imptype: 'json',
        impurl: 'SomeUrl/GetColumnsAndData',
        mtype: 'POST',
        impData: {
            '_search': 'false',
            'sidx': 'loc_short_name',
            'sord': 'asc',
            'page': '1',
            'rows': '25',
            'searchField': '',
            'searchOper': '',
            'searchString': ''
            // Add any additional, custom criteria
        },
        jsonGrid: {
            config: 'grid',
            data: 'data'
        }
    });
    

  10. 10.

    **Dynamic JQGrid From Data Table**
    $(document).ready(function () {
            var ColN, ColM, ColD, capEN;
            var sPath = window.location.pathname;
            var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
            //alert(sPage);
            $.ajax({
                url: sPage+'?method=getGridHeadData',
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: {},
                dataType: "json",
                success: function (data, st) {
                    if (st == "success") {
                        ColN = data.rowsHead;//jqgrid heading data
                        ColM = data.rowsM; // its column model
                        ColD = data.rows; // Data
                        createGrid();
                    }
                },
                error: function () {
                    alert("Error with AJAX callback");
                }
            });
    
            function createGrid() {
                jQuery("#AccountingCodesGrid").jqGrid({
    
                    datatype: 'json',
                    url: sPage+'?method=getGridData',
                    mtype: 'POST',
                    ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
                    serializeGridData: function (postData) {
                        return JSON.stringify(postData);
                    },
                    jsonReader: { repeatitems: false, root: "rows", page: "page", total: "total", records: "records" },
    
                    //data: ColD,
                    colNames: ColN,
                    colModel: ColM,
                    loadonce: true,
                    pager: jQuery('#pager'),
                    rowNum: 5,
                    rowList: [5, 10, 20, 50],
                    viewrecords: true
                })
    
    
            }
            jQuery("#AccountingCodesGrid").jqGrid('navGrid', '#Pager', { edit: false, add: false, del: false }, null, null, true, { multipleSearch: true });
            var height = $(window).height();
    
    
        });
    
    the code behind
     **In page load..................................................................**
    
    if (Request.QueryString["method"] == "getGridData")
                {
                    Request.InputStream.Position = 0;
                    StreamReader ipStRdr = new StreamReader(Request.InputStream);
                    string json = ipStRdr.ReadToEnd();
                    JavaScriptSerializer jser = new JavaScriptSerializer();
                    Dictionary<string,> dict = jser.Deserialize<dictionary><string,>>(json);
    
                    getGridData(int.Parse(dict["page"].ToString()), int.Parse(dict["rows"].ToString()), bool.Parse(dict["_search"].ToString()), dict["sord"].ToString());
                    Response.End();
                }
                else if (Request.QueryString["method"] == "getGridHeadData")
                {
                    getGridHeadData();
                    Response.End();
                }
    
    **Method to get data in json form----------------------------------------------------**
    public void getGridData(int page, int rows, bool _search, string sord)
            {
                DataTable dtRecords = dtSource;// Data Table
                int recordsCount = dtRecords.Rows.Count;
    
                JqGridData objJqGrid = new JqGridData();
                objJqGrid.page = page;
                objJqGrid.total = ((recordsCount + rows - 1) / rows);
                objJqGrid.records = recordsCount;
                objJqGrid.rows = ConvertDT(dtRecords);
    
                List<string> liob = new List<string>();
                foreach (DataColumn column in dtRecords.Columns)
                {
                    liob.Add(column.ColumnName);
                }
                objJqGrid.rowsHead = liob;
    
                List<object> colcontetn = new List<object>();
                foreach (var item in liob)
                {
                    JqGridDataHeading obj = new JqGridDataHeading();
                    obj.name = item.ToString();
                    obj.index = item.ToString();
                    colcontetn.Add(obj);
                }
                objJqGrid.rowsM = colcontetn;
    
                JavaScriptSerializer jser = new JavaScriptSerializer();
                Response.Write(jser.Serialize(objJqGrid));
    
            }
    

  11. 11.에 이것을 시도

    에 이것을 시도

    $.ajax(
        {
           type: "POST",
           url: "SomeUrl/GetColumnsAndData",
           data: "",
           dataType: "json",
           success: function(result)
           {
                colD = result.colData;
                colN = result.colNames;
                colM = result.colModel;
    
                jQuery("#list").jqGrid({
                    jsonReader : {
                        cell: "",
                        id: "0"
                    },
                    url: 'SomeUrl/Getdata',
                    datatype: 'jsonstring',
                    mtype: 'POST',
                    datastr : colD,
                    colNames:colN,
                    colModel :colM,
                    pager: jQuery('#pager'),
                    rowNum: 5,
                    rowList: [5, 10, 20, 50],
                    viewrecords: true
                })
           },
           error: function(x, e)
           {
                alert(x.readyState + " "+ x.status +" "+ e.msg);   
           }
        });
    setTimeout(function() {$("#list").jqGrid('setGridParam',{datatype:'json'}); },50);
    
  12. from https://stackoverflow.com/questions/2277962/jqgrid-dynamic-column-binding by cc-by-sa and MIT license