Tip #2 - Display JSON String from Object

Michael Schwarz on Thursday, April 12, 2007
Labels

Sometimes it is necessary to see i.e. the full result you will get inside the asynchronous callback function to see all properties. The AjaxPro JavaScript includes a method to convert a JavaScript object into a JSON string.

<script type="text/javascript">

function myInvoke() { MyNamespace.MyClass.MyMethod(1, 2, 3, myCallback);
}

function myCallback(res) { <span class="rem">// The following line will display a message box</span> <span class="rem">// with the JSON serialized string of the result.</span> alert(AjaxPro.toJSON(res.<span class="kwrd">value</span>));

<span class="rem">// To see all properties in the res object simple</span> <span class="rem">// use following command:</span> alert(AjaxPro.toJSON(res)); }

&lt;/script&gt;</pre>

For debugging this is very useful. Note: you should always check the res.Error property to see if there is any excption during your request.

On the server-side code you could use following line to get the JavaScript JSON representation of the .NET object:

<pre class="csharpcode">List&lt;<span class="kwrd">string</span>&gt; list = <span class="kwrd">new</span> List&lt;<span class="kwrd">string</span>&gt; ();
list.Add (<span class="str">"Michael"</span>);
list.Add (<span class="str">"Tanja"</span>);
list.Add (<span class="str">"Marc Julian"</span>);
list.Add (<span class="str">"Jan Oliver"</span>);

<span class="kwrd">string</span> json = AjaxPro.JavaScriptSerializer.Serialize (list);</pre>

The output of the json string will be:

```["Michael","Tanja","Marc Julian","Jan Oliver"]
```

You can use this feature to embedd any data structure already in the Page_Load event to your HTML output (JavaScript variable i.e.).