2

I am writing a data-driven web app using ASP.NET as the server-side technology to retrieve data from an SQL Server backend. Whilst I use server-side code to manipulate the output all works fine. However, I have written a few jQuery scripts (using Raphael.js) to draw interactive graphs based on the data. What is the best way to pass the dataset to the javascript functions?

At the moment I have ASP.NET output the data into some predictable format (like a table or similar):

<table>
    <tbody>
        <tr id='0'>
            <th>Risk:</th>
            <td class="val">10</td>
            <td>41.7%</td>
            <td class='col'>red</td>
        </tr>
        <tr id='1'>
            <th>Caution:</th>
            <td class="val">6</td>
            <td>25.0%</td>
            <td class='col'>orange</td>
        </tr>
    </tbody>
</table>

I then parse in a $(function() {}) block to extract the data:

$(function() {
    var values = [],
        labels = [];

    $("tbody > tr", this).each(function () {
        values.push(parseInt($("td.val", this).text(), 10));
        labels.push($("td.col", this).text());
    });
});

Then I use raphael to draw it into graphs. After it's completed, I set display: none on the data table.

Is there a better way to do this? The current solution requires me to be aware of (a) the outputted data format, (b) the js script and (c) the css that styles various aspects to make sure they are all 'in sync'. I wondered whether there is some way of passing datasets using JSON or something?

A minor downside to my current solution is that the raw data that is needed to create the graphs is still in the HTML (despite being hidden) and so can be viewed by anyone with half a brain.

1
  • could you post sample code Commented Aug 30, 2013 at 5:50

1 Answer 1

2

The easiest method to pass data from asp.net to javascript would be to write out your data into in a JSON object/array.

Having a variable at client side also allows you to update it using ajax calls to PageMethods.

There are various libraries in c# that will enable you to write objects to json.
I highly recommend Json.net

It can be as simple as

string json = JsonConvert.SerializeObject(table);
Sign up to request clarification or add additional context in comments.

2 Comments

So if I wrote the object to a JSON array, it would be available in the client-side code? At what point in the load cycle does the object get created: I assume it would be there at window.load? I'll check out Json.net, thanks!
You will have to write that json string to the output as a javascript variable using a call like ClientScriptManager.RegisterClientScriptBlock. After that it will be available on load

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.