1

I am trying to create an Asp.net app that displays a Google chart from data in an SQL database. Right now, I am just trying to pass the value of a C# int variable into a JavaScript variable. I'll figure out the rest later.

I have created the C# variable: public int timcs = 40;

I try to create the JavaScript variable and display it in and alert box: var timjs = '<%=timcs %>'; alert(timjs);

The resulting alert box just says <%=timcs %>.

If I do var timjs = <%=timcs %>; (no quotes) it doesn't work at all.

I have tried this many different ways and it never works. What am I doing wrong? All the code follows.

Thanks.

using System;
using System.Web.UI;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;


namespace TheBIGContest
{
    public partial class _Default : System.Web.UI.Page
    {

        public int timsc = 40;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // Bind Gridview  
                BindGvData();

                // Bind Charts  
                BindChart();
            }
        }

        private void BindGvData()
        {
            gvData.DataSource = GetChartData();
            gvData.DataBind();
        }

        private void BindChart()
        {
            DataTable dsChartData = new DataTable();
            StringBuilder strScript = new StringBuilder();

            try
            {

                dsChartData = GetChartData();

                strScript.Append(@"<script type='text/javascript'>  

                // Load the Visualization API and the corechart package.
                google.charts.load('current', { 'packages': ['corechart'] });</script>

                    <script type='text/javascript'>
                    // Set a callback to run when the Google Visualization API is loaded.
                    google.charts.setOnLoadCallback(drawChart);

                    var timjs = '<%=timcs %>';
                    alert(timjs);

                    // Callback that creates and populates a data table,
                    // instantiates the pie chart, passes in the data and
                    // draws it.

                    function drawChart() {

                    // Create the data table.
                    var data = new google.visualization.DataTable();
                    data.addColumn('string', 'Person');
                    data.addColumn('number', 'Points');
                    data.addRows([ ['Tim', 10], ['Barb', 20], ['Lee Ann', 30] ]);");

                //Set chart options
                strScript.Append("var options = {'title':'Points to Date', chartArea: { left: 43, top: 50, width: '80 %', height: '80%' }, backgroundColor: 'fff', 'width': 610, 'height':450, 'vAxis': { minValue: 0, ticks: [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]}, 'legend':'none'};");

                // Instantiate and draw our chart, passing in some options.
                strScript.Append("var chart = new google.visualization.ColumnChart(document.getElementById('chart_div')); chart.draw(data, options); }");
                strScript.Append("</script>");

                ltScripts.Text = strScript.ToString();
            }
            catch
            {
            }
            finally
            {
                dsChartData.Dispose();
                strScript.Clear();
            }
        }

        /// <summary>  
        /// fetch data from mdf file saved in app_data  
        /// </summary>  
        /// <returns>DataTable</returns>  
        private DataTable GetChartData()
        {
            DataSet dsData = new DataSet();
            try
            {
                SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
                SqlDataAdapter sqlCmd = new SqlDataAdapter("GetData", sqlCon);
                sqlCmd.SelectCommand.CommandType = CommandType.StoredProcedure;

                sqlCon.Open();

                sqlCmd.Fill(dsData);

                sqlCon.Close();
            }
            catch
            {
                throw;
            }
            return dsData.Tables[0];
        }
    }
}
  • its because you are using a literal string so its not executing the server side code. I would append the variable first in a separate .Append method without the literal (@). you could look at using interpolated and literal strings combined ($@) but you might need to escape some of the brackets etc. – WraithNath Aug 21 '17 at 14:12
  • I tried "How do I give JavaScript variables data from ASP.NET variables?" It didn't work. Something else is wrong. – Michaleen Oge Aug 21 '17 at 14:49
  • @WraithNath -- Could you expand on that explanation some? I'm kind of new at this. Thanks! – Michaleen Oge Aug 21 '17 at 14:52
  • Sure, if you put the '@' sign before a string, it means that the contents of the string should be treated literally, eg any apostrophes and other symbols will be put in the string as is (which you want for most of the javascript), however its also treating your server side code as a literal string and is just sent to the script string as that. you just need to exclude the part where you are using the server side code from the literal so it can be evaluated. If you see my answer, I have modified the code slightly so it gets the time on its own and then appends the rest of the script. – WraithNath Aug 21 '17 at 15:08

2 Answers2

1

The output tags <%= %> aren't relevant in this case because you are generating the client-side code from the code-behind class, rather than the actual aspx page.

Change to

var timjs = " + timcs + @";  ...

and it'll work.

DavidWainwright
  • 2,895
  • 1
  • 27
  • 30
0

its because you are using a literal string so its not executing the server side code. I would append the variable first in a separate .Append method without the literal (@). you could look at using interpolated and literal strings combined ($@) but you might need to escape some of the brackets etc.

    private void BindChart()
            {
                DataTable dsChartData = new DataTable();
                StringBuilder strScript = new StringBuilder();

                try
                {

                    dsChartData = GetChartData();

                    strScript.Append(@"<script type='text/javascript'>  

                    // Load the Visualization API and the corechart package.
                    google.charts.load('current', { 'packages': ['corechart'] });</script>

                        <script type='text/javascript'>
                        // Set a callback to run when the Google Visualization API is loaded.
                        google.charts.setOnLoadCallback(drawChart); ");

                    strScript.Append($"var timjs = {timsc};");

                    strScript.Append(@"
                        alert(timjs);

                        // Callback that creates and populates a data table,
                        // instantiates the pie chart, passes in the data and
                        // draws it.

                        function drawChart() {

                        // Create the data table.
                        var data = new google.visualization.DataTable();
                        data.addColumn('string', 'Person');
                        data.addColumn('number', 'Points');
                        data.addRows([ ['Tim', 10], ['Barb', 20], ['Lee Ann', 30] ]);");

                    //Set chart options
                    strScript.Append("var options = {'title':'Points to Date', chartArea: { left: 43, top: 50, width: '80 %', height: '80%' }, backgroundColor: 'fff', 'width': 610, 'height':450, 'vAxis': { minValue: 0, ticks: [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]}, 'legend':'none'};");

                    // Instantiate and draw our chart, passing in some options.
                    strScript.Append("var chart = new google.visualization.ColumnChart(document.getElementById('chart_div')); chart.draw(data, options); }");
                    strScript.Append("</script>");

                    ltScripts.Text = strScript.ToString();
                }
                catch
                {
                }
                finally
                {
                    dsChartData.Dispose();
                    strScript.Clear();
                }
            }
WraithNath
  • 17,658
  • 10
  • 55
  • 82