2016-03-10 130 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 }); 
      } 
     } 
    });