views:

241

answers:

2

Is there a way to get values from database (or XML file) using ASP.NET and then inject them into a JavaScript array?

+2  A: 

JavaScript running in the browser? The normal way would be to use JSON, either served as part of the page or as a response to an AJAX request. (Ignoring the X part, admittedly :)

I've found Json.NET very easy to use, in my limited experience with it.

I assume you already know how to get data out of the database, by the way? If not, I strongly suggest you separate these tasks - write (and test) the code to extract the data from the database, and entirely separately write the code to "transfer" it to the browser via JSON (or whatever). Start with hard-coded data which doesn't come from the database (but is in the same format). When you've got each part working independently, put them together.

Jon Skeet
Or just use JS literals when the page is generated.
Matthew Flaschen
Yup, that's a possibility - I just suspect that JSON is going to be easier to do in terms of reusing existing tools :)
Jon Skeet
(In the end, JSON *is* just JS literals, isn't it? Or am I missing something in your suggestion? Why not turn it into a full answer? :)
Jon Skeet
Well, JSON is a subset of JS literals, without the fun parts like arrays of "functions returning arrays of functions".
Matthew Flaschen
I have the both parts: getting data from db and a javascript to randomly select a value from array and display it in 10 second intervals. Now I need to put them together in an elegant way. I thought there may already be some known practices of doing that.
Alimzhan Zhanseitov
+2  A: 

Either of the approaches (AJAX or Literals) will work, for 'getting data'.

I tend to use literals when the page is generated for passing through 'configuration' and use AJAX requests (returning JSON) for retrieving data. Although with small amounts of data you might be better served just using literals embeded in your page. If you're doing this from an included JS file though you'll more likey want to use AJAX calls.

An example of a object literal might be ...

                var myConfig = 
                    {
                        AnArray: <%= mySerializedArrayFromTheServer%>,
                        ASerializedObject : <%=mySerializedObjectFromTheServer%>,
                        DataUri : 'http://someweburi/ThatReturns.json/',
                        SomeHardCodedValue : 'This is an message',
                        IdsUsedInPage: {
                                            GridContainer: 'uxGridContainerId',
                                            FormContainer: 'uxFormContainerId
                                        }

                    };

Remember that you can serialize to XML and use a parser in your Javascript too, although this is less common and usually has a performance overhead.

Lewis