简体   繁体   中英

jsTree Lazy Loading with C# & Web API

I am currently using jsTree v3.3.10 and attempting to load the structure via a Web API call.

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 EndPoint Code:

[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;
        }

I am getting json returned via the call and the appropriate contentType headers are there, but jsTree is not loading the tree correctly. This is the sample return of the JSON via postman:

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

But as you can see here, jsTree is not processing the JSON correctly.

树结果

Does anyone have any idea at all what I am doing wrong.

I figured this out. The WebAPI was returning type of string and jsTree does not do it's own parseJSON internally. To fix this I changed the return type of my end point to be an HTTPResponseMessage.

 public HttpResponseMessage GetKSBTree(String Type)

Then I format the response message and return it:

HttpResponseMessage rmMessage = new HttpResponseMessage() { Content = new StringContent(sJSON) };

rmMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

return rmMessage;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM