2016-03-10 155 views
1

我使用MVC和Handsontable來創建類似於Excel的顯示,但我無法讓控制器以Handsontable可以使用的格式返回json。以Handsontable兼容格式返回MVC Json

的MVC控制器返回JsonResult

return Json(results, JsonRequestBehavior.AllowGet); 

這是JS的函數,返回的數據:

function GetCategoryAttributeList() { 
    var categoryattributelist = ""; 
    $.ajax({ 
     async: true, 
     type: "POST", 
     url: "[myurl]/PopulateHOT", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (msg) { 
      categoryattributelist = msg; 
     } 
     return categoryattributelist; 
    }); 

在Firebug中,我可以看到返回的數據:

[{ StockCatalogueItemId=235031, SKU="03121017593518"}, { StockCatalogueItemId=235032, SKU="03121018032318"} ...etc 

我調用函數並將結果賦值給一個變量:

var categoryattributelist = GetCategoryAttributeList(); 

然後使用結果的初始化代碼:

var hotElement = document.getElementById('#example'); 
    var hot = new Handsontable(hotElement, { 
     data: categoryattributelist 
    }); 

此時,數據現在看起來略有不同(請注意,「對象」已經每個元素之前被添加):

[Object { StockCatalogueItemId=235031, SKU="03121017593518"}, Object { StockCatalogueItemId=235032, SKU="03121018032318"} ...etc 

所以玩的當前狀態是控制檯錯誤,我似乎無法超越這個進步:

TypeError: rootElement is null 

任何想法?

+0

什麼是預期的數據格式?看看[本教程](https://docs.handsontable.com/0.23.0/tutorial-quick-start.html),它看起來是一個數組或數組(其中返回一組對象) –

+0

硬編碼var categoryattributelist = [[「StockCatalogueItemId」,「SKU」],[235031,235032],[「03121017593518」,「03121018032318」]];'爲你工作? –

+0

根據[this](https://docs.handsontable.com/0.23.0/tutorial-data-sources.html),它可以處理各種數據源(包括對象數據源)。 – markpsmith

回答

0

嘗試使用AJAX回調中的初始化代碼,並看看是否能工程

function GetCategoryAttributeList() { 
    $.ajax({ 
     async: true, 
     type: "POST", 
     url: "[myurl]/PopulateHOT", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (data) { 
      //handle returned data from service 
      var hotElement = $('#example'); 
      if(hotElement){ 
       var hot = new Handsontable(hotElement, { data: data }); 
      } 
     } 
    });