2013-04-25 2 views
0

나는 검도 UI 그리드를 기반으로 다음과 같은 코드가 있습니다 :서버 사이드 페이징을 사용하여 검도 UI 그리드에 데이터를로드하는 방법은 무엇입니까?

// build grid columns 

    // the check box column is always visible for all users 
    var columns = [{ 
     field:'<input id="masterCheck" class="check" type="checkbox" /><label for="masterCheck"></label>', 
     template: '<input class="check rowSelect" id="${id}" type="checkbox" /><label for="${id}"></label>', 
     filterable: false, 
     width: 33, 
     sortable: false // may want to make this sortable later. will need to build a custom sorter. 
    }]; 

    // build the rest of the columns using data provided by the server 
    var metrics = initialData.metric; 
    for (var i=0; i < metrics.length; i++) { 
     var metric = metrics[i]; 
     var column = {}; 
     column.field = metric.qualifiedName; 
     column.title = metric.label; 
     column.width = metric.colWidth; 
     // initially hide all columns. we'll know exactly which ones to show after a search 
     column.hidden = true;   
     column.type = metric.type; 

     // handle special considerations 
     if (column.type === 'float' || column.type === 'int') {   

      // format all floats to two decimal places 
      if (column.type === 'float') { 
       column.format = '{0:n2}'; 
      } 
      // the grid only has a type of number.    

      column.attributes = {'class' : 'right-align'}; 

      var field = column.field; 

      // create a closure to build a function that captures the field variable value 
      // in this iteration. Immediately execute the anonymous outer function so 
      // that the inner function is returned as assignment to the footerTemplate 
      // variable. The param data will be passed to the function by the grid. 
      // That function then executes the buildFooter which has the right field value 
      // due to the closure. notice that each invocation of the outer function 
      // creates a new scope chain that adds a new inner function. 
      column.footerTemplate = (function(field, columnType) {return function() { return buildFooter(field, columnType); }; })(field, metric.type); 
      column.type = 'number'; 

     } else if (column.type === 'date') { 
      column.format = '{0:yyyy-MM-dd}'; 
     } else if (column.field === 'attachments') { 
      //column.field = 'text'; 
      // use a template defined in search.jsp to style this complex 
      // object 
      column.template = kendo.template($('#attachmentTemplate').html()); 
      column.sortable = false; 
      column.filterable = false; 
     } else if (column.type === 'list') { 
      column.type = 'string'; 
     } 

     columns.push(column);   
    } 

    var toolbarItems = [{ name: 'custom', text: 'Filter', className: 'filterClass k-state-disabled', imageClass: 'k-icon k-i-funnel'}, 
         { name: 'view', text: 'View', className: 'viewClass k-state-disabled', imageClass: 'k-icon k-i-search' }]; 
    // only show build the edit and delete buttons in the toolbar if the 
    // user has permissions 
    if ($('#hasAdminControls')[0]) { 
     toolbarItems.push({ name: 'edit', text: 'Edit', className: 'editClass k-state-disabled' }); 
     toolbarItems.push({ name: 'destroy', text: 'Delete', className: 'deleteClass k-state-disabled' }); 
    } 

    var options = { 

     autoBind: false, 
     dataBound: function() { 

      alert('dataBound'); 
      for(var i =0; i < checkedRows.length; i++){ 
       $('#'+ checkedRows[i]).attr('checked','checked'); 
      }    
      $('.rowSelect').click(setGridControlsState); 
      setGridControlsState(); 

      $('.k-grid-content').removeHighlight(); 
      $('.k-grid-content').highlight(uniqueHighlights); 
     },  
     dataSource: { 
      //type: 'json', 
      //batch: 'true', 
      serverPaging: true, // we may need to use paging for performance reasons 
      //schema: { 
      // total: 'total'//function(response) { console.log(response); alert('hi2'); return 500; } 
      //}, 
      //schema: { 
       //model: Acquisition // if we use a model then complex objects' fields all have string type 

      pageSize: 10, 

      //serverFiltering: true, // we may want to use this in the future if client filtering becomes a performance issue 
      //serverSorting: true, // we may want to use this in the future if client sorting becomes a performance issue 
      transport: { read: 
      function(options) { 

       var setupOptions = { 
         success: function(data, statusText, xhr, $form) {options.success(data); loadSearch(data, statusText, xhr, $form)}, 
         type: 'POST', 
         dataType: 'json', 
         data: {skip: options.data.skip, take: options.data.take}, 
         url: '../search.x', 
         error: errorHandler.handle, 
         timeout: 50000 
       }; 
       $('#searchForm').ajaxSubmit(setupOptions); 
      } 

      } 
     }, 
     height: 600, 
     pageable: { 
      //numeric: false, 
      //previousNext: false, 
      messages: { 
       display: "{2} Acquisitions" 
      }, 
      pageSizes: true 
     }, 
     sortable: true, 
     resizable: true, 
     filterable: true, 
     toolbar: toolbarItems, 
     columns: columns 
    }; 

    // create the grid using the above options 
    $('#resultsGrid').kendoGrid(options); 

    // for purely aesthetic purposes, move the toolbar to the bottom (by default it's at the top) 
    $('#resultsArea').find('.k-grid-toolbar').insertAfter($('#resultsArea .k-grid-footer')); 
    var grid = $('#resultsGrid').data('kendoGrid'); 
    grid.refresh(); 

그리드는 처음에는 숨겨져 있지만 검색 양식 제출 후 보여줍니다. 검색 양식이 제출 될 때, 다음과 같은 기능이 실행됩니다

function startSearch(evt) { 
    evt.preventDefault(); 

    showLoadingGrid(); 
    var grid = $('#resultsGrid').data('kendoGrid'); 
    grid.dataSource.read(); 

} 

grid.dataSource.read() 함수를 호출 transport.read에 의해 시작된 서버에 AJAX 호출이 발생합니다. 그러나 kendo가 오류를 throw하기 때문에 success 함수가 호출되지 않습니다. 상태 d.oneOfMyObjects는 정의되지 않은 kendo.web.min.js입니다 (9 행). json 응답을 보면 서버의 json 객체가 여러 개 있습니다. 객체 중 하나는 객체의 배열입니다. 이러한 각 객체에는 oneOfMyObjects라는 속성 (객체)이 있습니다. 각 oneOfMyObjects는 null이 아닙니다. 그래서 kendo가 실패하는 이유를 모르겠습니다. 나는 kendoui.2012.3.1315를 사용하고 있습니다. 검도에서이 오류가 발생하지 않도록하고 loadSearch 콜백 함수를 호출 할 수있게하려면 어떻게해야합니까?

두 번째 편집 오류는 options.success (data)의 성공 함수에서 발생합니다.

편집 서버의 출력을 포함하는 편집 질문입니다. 똑같은 출력이 페이지 매김없이 잘 작동한다는 것도 기억하십시오 (데이터 보안 목적으로 출력을 수정해야만했습니다 ... 같은 구조를 유지하려고했지만 실수로 JSON을 준수하도록 실수로 변경하지는 않았습니다) :

{ 
    "total":500, 
    "displayFields":["summary","page","take","pageSize","skip"], 
    "object":[{ 
     "id":16835, 
     "date":-2208967200000, 
     "type":"Needs Value", 
     "nestedObject1":{ 
      "id":16870, 
      "name":"Not Specified", 
      "region":{ 
       "name":"Needs Value" 
      } 
     }, 
     "oneOfMyObjects":{ 
      "id":16923, 
      "name":"Needs Value" 
     } 
    }, { 
     "id":16836, 
     "date":-2208967200000, 
     "type":"Needs Value", 
     "nestedObject1":{ 
      "id":16873, 
      "name":"Not Specified", 
      "region":{ 
       "name":"Needs Value" 
      } 
     }, 
     "oneOfMyObjects":{ 
      "id":16925, 
      "name":"Needs Value" 
     } 
    }, /* 8 more records */] 
} 

3 편집 당신은 어디에서 데이터를 찾을 수 schema에 지정하지 loadSearch 기능을

function loadSearch(data, statusText, xhr, $form, options) { 

    if (data.validationError) { 
     // TODO we need to look at the message from the reply 
     // right now though only date validation errors will exist 
     dialog.show('Error', 'Please enter dates formatted as yyyy-mm-dd.'); 
     global.loadingIndicator.hide(); 
     return; 
    } 

    checkedRows = []; 
    var object= data.object; 

    var grid = $('#resultsGrid').data('kendoGrid'); 

    // clear any filters. This also help with an issue where no 
    // rows are shown due to a filter. 
    grid.dataSource.filter({}); 


    // set the search results data in the grid 
    grid.dataSource.data(object); 

    // show columns that are either a user preference 
    // column (or default set if user has no preferences) 
    // or a field matching search data 

    // let's only hide/show the delta between 
    // previously viewed cols and new cols to display 
    // since it's much faster than hiding all old 
    // and then displaying all new cols 
    var oldCols = $('#displayColumns').val() || []; 

    // the server tells the UI which fields to display 
    // based on user preference and fields that that 
    // have matching search data 
    var newCols = data.displayFields; 

    var removedCols = oldCols.diff(newCols); 
    for (var i in removedCols) { 
     $('#displayColumns option[value="' + removedCols[i] + '"]').removeAttr('selected'); 
     grid.hideColumn(removedCols[i]); 
    } 

    var addedCols = newCols.diff(oldCols); 
    for (var i in addedCols) { 
     grid.showColumn(addedCols[i]); 
     $('#displayColumns option[value="' + addedCols[i] + '"]').attr('selected', 'selected'); 
    } 

    // we have to tell the chosen overlay that we updated the list 
    $('#displayColumns').trigger('liszt:updated'); 

    // we have to keep track of the current selected values 
    // so that when the user changes to selection we'll 
    // be able to compare to the original selection 
    // and now what they changed. 
    $('#displayColumns').data('chosen-values', $('#displayColumns').val()); 


    // display the results 
    grid.refresh(); 

    realignFooter(); 

    // Highlight search matches so the user can easily see 
    // why the record is in the result grid. 
    // Unfortunately, the highlights library takes a comma-delimited list. 
    // It's problematic when the search results contain a comma. 


    // remove previous highlights 
    //$('.k-grid-content').removeHighlight(); 

    uniqueHighlights = data.uniqueHighlights || []; 
    $('.k-grid-content').removeHighlight(); 
    $('.k-grid-content').highlight(uniqueHighlights); 

    // reset the controls since all checkboxes have been cleared 
    setGridControlsState(); 

    // register event to capture clicks on grid checkboxes 
    // we can't do this during initialization b/c the checkboxes 
    // are not yet built. Note: we don't have to remove 
    // the events associated with previous checkboxes as 
    // jquery should automatically do this. 
    $('.rowSelect').click(setGridControlsState); 

    // remove loading indicator 
    global.loadingIndicator.hide(); 

    // style the UI to give the user an option to save the columns again 
    $('#saveCols > span').empty().text('Save Columns'); 
    $('#saveCols').removeClass('k-state-disabled'); 

} 
+0

답장에 응답 예를 포함 시키시겠습니까? – OnaBai

+0

'transport.read'에는'success' 옵션이 있습니까? 설명서에서 찾을 수 없습니다 ... – OnaBai

+0

맞습니다. 그러면 loadSearch가 호출되지 않는 이유가 설명됩니다. 하지만 성공 함수를 호출해야합니다. 그래서, 나는 transport.read가 함수를 가리 키도록 나의 질문을 편집했다. 이 함수의 AJAX 호출은 [Malsup form plugin] (http://malsup.com/jquery/form/)을 통해 이루어집니다. – James

답변

1

을 포함합니다.

schema : { 
    data : "object", 
    total: "total" 
} 

결과를 어디에서 찾을 지 말하지 않는다는 사실은 어떤 필드라도 표시 할 수있게합니다.

성공 함수는 결코이라고 불리지 않습니다. 이러한 옵션은 존재하지 않습니다 (AFAIK).

+0

감사합니다. OnaBai. 이것은 내가 본 오류를 방지합니다. 그러나 전체가 설정되지 않았습니다. 따라서 클라이언트 UI는 데이터의 한 페이지 만 존재한다고 생각합니다. 합계는 어떻게 적절하게 설정 될 수 있습니까? 또한, 최신 편집을 위해 위를 보시겠습니까? 나는 success 함수가 필요하고 Malsup 폼 플러그인을 사용하고자하기 때문에 함수를 가리 키기 위해 transport.read를 변경해야했다. – James

+0

죄송합니다. 실제로 schema.data를 객체로 설정하는 중에 오류가 발생합니다. options.success (data)에서 오류가 발생합니다. 오류는 TypeError입니다. e.indexOf가 함수가 아닙니다 (kendo.web.min.js (9 행)). 나는 그 전화를 제거 할 수 있으며 오류는 사라지지만 총은 설정되지 않습니다. – James

0

나는 당신에게 도움이 될만한 것이 무엇인지 명확히하기 위해 주석으로 만들었지 만 코드를 보는 것이 더 어려웠을 것이므로 여기에서 시작하여 내가 당신의 질문에 완전히 대답 할 수 있는지 알아 보겠다.

transport: { 
    read: { 
     url: '@Url.Action("_List", "Check")', 
     data: gridParams, 
     type: 'POST' 
    }, 
function gridParams() { 
     return { 
      Field1: $('#fd1').val(), 
      Field2: $('#fd2').val(), 
      Field3: $('#fd3').val() 
     }; 
    } 

fd1-3은 당신이 컨트롤러에 매개 변수를 전달해야하는 필드의에 대한 검색이 아이디의를 형성 할 것이다. 컨트롤러 동작에 대한 다음

, 그리고

[HttpPost] 
    public JsonResult _List(string Field1, DateTime? Field2, DateTime? Field3, int skip, int take) 
    { 

당신은 단지 => w.fd1 == 승 필드 1 & & w.fd2 당신의 db.TableName.Where을 (변경하려면이 매개 변수를 사용하는 것이 == 필드 2 || w.fd3 == Field3) .Skip (건너 뛰기)

등등.

+0

답변 해 주셔서 감사합니다. 명시 적으로 [Malsup form plugin] (http://malsup.com/jquery/form/)을 사용하여 값을 가져올 필요없이 양식 데이터를 가져 오는 방법이 있습니다. 원래 질문에 대한 편집을 수행하여 내가이 작업을 수행하고 있음을 나타냅니다. 오류를 극복하기 위해 객체로 읽으려고했는데, 폼 플러그인을 사용하고 싶기 때문에 실제로 함수에 설정해야합니다. 위의 수정을 참조하십시오. 변경 죄송합니다. – James

0
var dataSource = new kendo.data.DataSource({ 
     serverPaging: true, 
     serverSorting: true, 
     pageSize : 15, 
     transport : { 
     read : { 
      url : getEmployeeData, 
      dataType : "json" 
     }, 
     parameterMap : function(options, operation) { 
      if (operation == "read") { 
       return { 
        page: dataSource._page, 
        pageSize: dataSource._pageSize 
      }; 
     } 
     } 
    }, 
    batch : true, 
    schema : { 
     data: "data", 
     total: "total", 
     model : { 
     id : "id", 
     fields : { 
      name : { 
      validation : { 
       required : true 
      } 
      } 
     } 
     } 
    } 
    }); 
관련 문제