Jquery + jstree in.net - webservice response form?

I first played with jstree (1.0rc2) + jquery (1.4.2) with C # .net, and although I got it working, there are a couple of things that I don’t understand about how the data is provided to the tree by the webservice service that I use to populate the tree (using ajax and json_data plug-in). I was hoping that someone with more experience using jstree could give some insight.

The jstree configuration looks like this:

"json_data": { "ajax": { "url": "GetTree.asmx/GetChildren", "type": "POST", "contentType": "application/json; charset=utf-8", "dataType": "json", "data": function(n) { var result = "{'id':'" + (n.attr ? n.attr("id").replace("node_", "") : "0") + "'}"; return (result); } } } 

GetTree.asmx GetChildren Method:

  [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Xml )] public string GetChildren(string id) { List<jsTreeNode> jsTree = new List<jsTreeNode>(); //... (build the tree as needed) JavaScriptSerializer serializer = new JavaScriptSerializer(); return(serializer.Serialize(jsTree)); } 

Question 1: So everything works fine, so what's the problem? The problem is "ResponseFormat = ResponseFormat.Xml". For a while, I struggled for this to work, because it didn't work when it was set to ResponseFormat.Json, and that is what I expect. In this situation, the web service does not report errors or jQuery when parsing the json response, but the tree will appear empty.

Looking at the HTML output of a web service, I see no difference between what was done anyway. I was hoping someone would be able to explain why this works (counterintuitively) and why this does not work with ResponseFormat.Json, and if this indicates something else, I could be wrong.

Question 2: Typically, a web service or a web handler?

Would using a shared web handler (ashx) be a more efficient way to do this anyway? Is there a significant difference in the overhead required for a standard web service compared to a regular web handler? Since my goal is mainly to precisely control what is output (and using the json data format in the web service doesn't seem to work the way I want it), I'm not sure what benefit if any using a web service here, and not just completely disabling it. On the other hand, it works now, so maybe I should leave one alone.

+4
source share
3 answers

Seeing that this question has almost 600 views and there are no answers, I thought I would answer it myself (since I understood this a long time ago).

Using ScriptMethod really not suitable for communicating with jQuery ajax. Although this can be done, you will notice that what I am doing above returns a string with the data that I encoded in JSON using the JavascriptSerializer.

However, the use of ScriptMethod automatically includes serialization / deserialization designed to communicate with the Microsoft AJAX map. Since serializing a clean line without an object wrapper generally results in the same line (whether I return the XML or JSON format), it basically worked, but what actually happened inside was serialized twice.

So what I had to do, at a minimum, was:

public List<jsTreeNode> GetChildren(string id)

that is, the return type must be the actual data type, not a string of serialized data.

However, this will still not be entirely correct, as Microsoft's methods wrap the return value in object d . I could extract this in Javascript to get the internal data. But if something like jsTree expects data in a predefined format, this may not be working.

The best solution does not use WebServices, use generic handlers (ashx) instead. This gives you complete control over the format and handling of input and output. You may need to do a little to set yourself up in a convenient way, but the disappointment that you cannot miss the parts of WebService processing that you do not need makes it appreciate it well.

+4
source

Sorry, I have to disagree with your answer. The 3.5-framework program does support Json serialization and web services (and for 2.0 you can use Newtonsoft.Json). Please check out my JSTree ASP.NET web control demo at http://code.zyky.com/jsTreeView/Default.aspx and http://asp-net-elephant.blogspot.com/2012/01/how- to-use-jstree-in-aspnet-web-forms.html for an example of both. Hope this helps.

+1
source

As for question 1 (I can't talk to Q2), I got a web service to pass JSON back to the jsTree plugin. Although I admit that WCF and REST are more modern approaches, and undoubtedly better in the long run, we still use asmx services and they do their job. But it was not easy: I spent some time trying to get the exact syntax for working in JS so that jsTree gets its data object from the ASP.NET web service. As the OP points out in its solution, the problem is not so much in my JS and the plugin wiring, but in the fact that I had JSON data that my web service returned. It looked like JSON, but it was a string representation of a simplified JSON object.

To fix this, I had to deserialize and serialize my json string (I understood this from fooobar.com/questions/122476 / ... ) and the resulting object was successfully used by jsTree, Here is my web service:

 Imports System.Web.Script.Serialization Public Function GetJsonData() As String Dim jss As JavaScriptSerializer = New JavaScriptSerializer ' IMPORTANT: do not use single quotes ' in JSON string, use "" Dim jsonData As String = "" & _ "{ ""text"": ""CONTACTS"", ""children"": [ { ""text"": ""CUSTOMER"", ""column"": ""CLASS"", ""children"": [ { ""text"": ""Excelo Communications"", ""column"": ""COMPANY"", ""children"": [{ ""text"": ""Fred Shorts"", ""column"": ""CONTACT"" }] } ] }, { ""text"": ""USER"", ""column"": ""CLASS"" } ] }" Dim o As Object = Nothing Try ' deserialize the JSON into an Object, ' shout out to: /questions/122476/deserializing-json-in-visual-basic/747174#747174 o = jss.Deserialize(Of Object)(jsonData) o = jss.Serialize(o) Context.Response.Clear() Context.Response.ContentType = "application/json; charset=utf-8" Catch ex As Exception // log something End Try Return o End Function 

On the client, I initialized jsTree in a script as follows:

 $(document).ready(function () { var sURL = "../dataIO.asmx/GetJsonData"; var dataIn = ""; $.ajax({ async: true, type: "POST", url: sURL, dataType: "json", data: dataIn, contentType: "application/json; charset=utf-8", success: function (data) { console.log("data obj:" + data); createJSTrees(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest.statusText + "(status=" + XMLHttpRequest.status + "): " + XMLHttpRequest.responseText); } }); }); function createJSTrees(jsonData) { $("#jstree_dataNav").jstree({ "core": { "data": jsonData } }); $("#jstree_dataNav").on("changed.jstree", function (e, data) { console.log(data.selected); }); } <div id="jstree_dataNav"></div> 

jsTree has a somewhat alternative syntax, while you are calling a web service in the core.data section, but I could not get this to work. Instead, I call my web service through ajax, and then pass the JSON data object to the function that initializes the jsTree plugin, and jsTree just used the object passed inside the data :.

0
source

All Articles