Katstevens
Katstevens

Reputation: 1571

Pass data from ASP.NET to Javascript

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.

Upvotes: 2

Views: 3142

Answers (1)

nunespascal
nunespascal

Reputation: 17724

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);

Upvotes: 2

Related Questions