mister_b
mister_b

Reputation: 307

Calling a javascript library from ASP.NET

This is a fairly newbie question I'm sure. I'm looking at replacing our server side charting library with the open source javascript library 'flot'. I can use ASP in the javascript used to call the library as per the following example

<div id="placeholder" style="width: 600px; height: 300px;">
</div>
<script type="text/javascript">
    $(function () {
        var d = [<%
        for (var i = 0; i < 10; i++) {
            if(i > 1)  
                Response.Write(",");  

            Response.Write("[" + i + "," + Math.Sin(i) + "]");
        }%>];

        $.plot($("#placeholder"), [d]);
    });
</script>

This works a charm but what I really need to do is display data from a method in my code behind file (and ultimately a database). A quick Google suggests that I need to use AJAX to accomplish this but I would like to do it on page load.

It strikes me as something that should be simple to do but then I am relatively new to web development (I'm a windows forms developer by trade and an MS Certified one at that so I know my way around C#).

Any help or pointers would be greatly appreciated.

Cheers,

Neil.

Upvotes: 2

Views: 233

Answers (3)

Ralph Lavelle
Ralph Lavelle

Reputation: 5769

Very broadly, what you might consider is this - using jQuery AJAX to call a 'code-behind' page to generate your 'd' variable, and then when that returns from the server, using it in your $.plot($("#placeholder"), [d]); statement.

You can create a handler class, say 'GenerateData.ashx' which gets stuff from the database, and Response.Write()s it all out as your list of i and Sin(i) values, then

$(function () {
    $.ajax({
        url: "GenerateData.ashx",
        success: function(data){
            $.plot($("#placeholder"), data);
        }
    })
};

Something along those lines...

Upvotes: 1

Rupendra
Rupendra

Reputation: 608

You can call some C# function in your Java script code using :

<%# C#_FunctionName(parmVal1,ParamVal2) %>

it will return the return value of the C# function, or execute the C# function.

Thanks

Upvotes: 0

Tom Robinson
Tom Robinson

Reputation: 8528

This isn't necessarily the best practice solution, but you could generate the JavaScript dynamically on the server during page load.

This would be a good starting point: MSDN: ClientScriptManager.RegisterClientScriptBlock Method

Upvotes: 0

Related Questions