【问题标题】:jsTree Lazy Loading with C# & Web API使用 C# 和 Web API 的 jsTree 延迟加载
【发布时间】:2020-10-03 15:16:33
【问题描述】:

我目前正在使用 jsTree v3.3.10 并尝试通过 Web API 调用加载结构。

JavaScript:

$('#ksbBrowser').jstree({
                core: {
                    data: {
                        type: 'GET',
                        dataType: 'json',
                        contextType: 'application/json',
                        url: function (node) {
                            if (node.id == "#") {
                                return '/api/search/talent/ksbtree/root';
                            }
                            else {
                                return '';
                            }
                        },
                        data: function (node) {
                            return { id: node.id };
                        }
                    }
                }
            });

C# WebAPI 端点代码:

[HttpGet, Route("api/search/talent/ksbtree/{Type}")]
        public String GetKSBTree(String Type)
        {
            List<DataModels.JSTreeNode> lNodes = new List<JSTreeNode>();
            String sJSON = "";

            switch (Type)
            {
                case "root":
                    var first = new[] {
                        new {
                            id = "root-id",
                            text = "KSBs",
                            state = new { opened = true },
                            children = true
                        }
                    };

                    sJSON = JSONHelper.Serialize(first);

                    break;
                default:
                    break;
            }


            return sJSON;
        }

我正在通过调用返回 json,并且存在相应的 contentType 标头,但 jsTree 未正确加载树。这是通过邮递员返回的 JSON 示例:

"[{\"id\":\"root-id\",\"text\":\"KSBs\",\"state\":{\"opened\":true},\"children\":true}]"

但正如您在此处看到的,jsTree 没有正确处理 JSON。

有没有人知道我做错了什么。

【问题讨论】:

    标签: javascript c# asp.net jstree webapi


    【解决方案1】:

    我想通了。 WebAPI 正在返回字符串类型,而 jsTree 在内部没有自己的 parseJSON。为了解决这个问题,我将端点的返回类型更改为 HTTPResponseMessage。

     public HttpResponseMessage GetKSBTree(String Type)
    

    然后我格式化响应消息并返回:

    HttpResponseMessage rmMessage = new HttpResponseMessage() { Content = new StringContent(sJSON) };
    
    rmMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
    
    return rmMessage;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多