2

I am working on a ASP.NET/C# web application. I am writing a Jquery script. I would like to know what is the best way to add data to the script from an SQL database . Here is a quick example showing what I would like to do:

Suppose I have a database like this

Name           Color
------------+---------------+
Tom            FF0000              
Kate           00FF00               
John           0000FF    

In my script I want to do this:

$(function(){
    $('#main').Picture({
        colors: {Tom:'#FF0000', Kate:'#00FF00', John:'#0000FF'}
    });
});

the colors should be red from the database and not hard-coded.

What is the best way to insert the colors in the correct place in my code? Should I do it in a literal control and inject the script from the code behind?

Another example:

$('#location').html('Here we put the text that I got from the database');

Thank you for any help

2 Answers 2

1

Suggested Scenario: Get you data from your SQL database normally like you used to, then fill the data into any web control of your choice (I prefer to use a HiddenField in this case) then the Hidden field will be available to your Javascript/jQuery code.

Example: here are the steps you need to follow in order to get this problem fixed:

1- Create an asp:HiddenField control in your page with a proper ID (ex: 'hfMyData').

2- In your c# code, get your data from your database:

var mydata = // code to get the data from your Database

3- Fill the HiddenField value with your data:

hfMyData.value = mydata;

4- In your jQuery code Ready() function, use code similar to this:

var myDatabaseData = $("#hfMyData").val();

5- Now you have the data from your Database (myDatabaseData), use it as you want.

Sign up to request clarification or add additional context in comments.

Comments

0

What I've done in the past (although it's a bit quick and dirty), is create a public property on the page, then call it in the jQuery using the <% %> tags. That way you can set the property in the code behind via the DB call, then pull them through as required.

Not very scalable, but worked well for the scenario I required (needed a twitter handle).

Comments

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.