Fill an array of Javascript with the result of a SQL Server stored procedure

0

I have a stored procedure which, when executed, throws me a table dynamically. I would like that table to be stored in an array of Javascript, regardless of the number of fields or rows.

Is there any way to fill in from a SQL Server stored procedure?

Code C #:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

namespace Dash_Femsa
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            clsConexioncs conexion_server = new clsConexioncs();

            conexion_server.Conexion = ConfigurationManager.ConnectionStrings["DefaultDW"].ToString();

            //store 
            try 
            {

                conexion_server.PreparaComandoSP("prm_spFEMSA_SemanasIndicadoresTelemetria");

                conexion_server.LlenaComboConConsulta(lista_fechas, "Semana", "RangoFechas");                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString().Trim());

            }
        }
    }
}

It is important to mention that the procedure is executed from a C # method with web form, and it is sent to a page to generate graphs from the Google chart. I hope to have explained. Thanks.

This is my Javascript code:

<script type="text/javascript">
    google.charts.load('current', { 'packages': ['bar'] });
    google.charts.setOnLoadCallback(drawStuff);

    function drawStuff() {
        var data = new google.visualization.arrayToDataTable([
          ['Opening Move', 'Total'],
          ["Irapuato", 150],
          ["Celaya", 115],
          ["Coecillo", 94],
          ["Oriente León", 90],
          ['León Sur', 38]
        ]);

        var options = {
            title: 'Telemetría FEMSA',
            width: 900,
            legend: { position: 'none' },
            chart: {
                title: 'Telemetría FEMSA',
                subtitle: 'Total por zona'
            },
            bars: 'horizontal', // Required for Material Bar Charts.
            axes: {
                x: {
                    0: { side: 'top', label: 'Totales' } // Top x-axis.
                }
            },
            bar: { groupWidth: "90%" }
        };

        var chart = new google.charts.Bar(document.getElementById('grafica_semanal'));
        chart.draw(data, options);
    };
</script>
    
asked by Ric_hc 18.02.2017 в 01:27
source

3 answers

1

H.o.l.a, What you can do in these cases is to create a webservice that obtains your information from the database and consume this webservice from the side of the client with jquery. Another solution is to use this library to create the graphics: link . With this library you can load the graph data from the server side.

    
answered by 23.02.2017 в 18:00
1

With these instructions they will generate the graph:

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

namespace SistemaDashBoardFEMSA
{
    public partial class Graficas : System.Web.UI.Page
    {
        int[] barras = new int[3];

        string[] nombs = new string[3];


        protected void Page_Load(object sender, EventArgs e)
        {
            ObtenerDatos();
        }


        //get data
        protected void ObtenerDatos()
        {
            DataSet resultado = new DataSet();            

            clsConexioncs conexion_server = new clsConexioncs();

            conexion_server.Conexion = ConfigurationManager.ConnectionStrings["DefaultDW"].ToString();


            conexion_server.PreparaComandoSP("sp_telemtria_femsa");

            resultado = conexion_server.EjecutaComandoDataSet();




            foreach (DataRow row in resultado.Tables[0].Rows)
            {


            }

            Graficas_Semanal.Series["Series"].Points.DataBindXY(nombs, barras);

        }

    }
}

Now what I'm doing is adjusting it to the tables I need.

Result of the sp:
Irapuato 150
Celaya 115
Coecillo 94
East León 90
South Lion 38

I hope and serve you.

    
answered by 23.02.2017 в 18:47
0
  

Improve publications through edits or comments. Make edits to correct errors, improve the format or clarify the meaning of a publication.

     

Stack Overflow in Spanish is a question and answer site. It is not a discussion forum.

About your problem. Your question could be given as wide, but not to extend the "FORO" what are you doing?

Use Response.Write to generate the array you need . For the example you can get it from a property or a static method.

CodeBehind:

using System;
using System.Data;
using System.Text;
using System.Web.UI;

namespace WebApplication2
{
    public partial class WebForm1 : Page
    {
        protected string InformacionArray
        {
            get { return ViewState["GRAFICO"] as string; }
            set { ViewState["GRAFICO"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            InformacionArray = MetodoEstatico();
        }

        protected static string MetodoEstatico()
        {
            var table = new DataTable();
            table.Columns.Add("Texto", typeof(string));
            table.Columns.Add("Numero", typeof(int));

            for (var i = 0; i < 10; i++)
            {
                var row = table.NewRow();
                row["Texto"] = "item " + i;
                row["Numero"] = i;
                table.Rows.Add(row);
            }

            var sbArrayPrueba = new StringBuilder();
            sbArrayPrueba.Append("[");
            for (var i = 0; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];
                var separador = i != table.Rows.Count - 1 ? "," : "";
                sbArrayPrueba.AppendFormat("['{0}', {1}]{2}", row["Texto"], row["Numero"], separador);
            }
            sbArrayPrueba.Append("]");

            return sbArrayPrueba.ToString();
        }
    }
}

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>
        (function() {
            // Obtenido desde una Propiedad de la página
            var miArrayDePropiedad = <%= InformacionArray %>;
            alert(miArrayDePropiedad);

            // Obtenido de un método estático
            var miArrayDeMetodo = <%= MetodoEstatico() %>;
            alert(miArrayDeMetodo);
        })();

    </script>

</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>

Result:

<script>
    (function() {
        // Obtenido desde una Propiedad de la página
        var miArrayDePropiedad = [['item 0', 0],['item 1', 1],['item 2', 2],['item 3', 3],['item 4', 4],['item 5', 5],['item 6', 6],['item 7', 7],['item 8', 8],['item 9', 9]];
        alert(miArrayDePropiedad);

        // Obtenido de un método estático
        var miArrayDeMetodo = [['item 0', 0],['item 1', 1],['item 2', 2],['item 3', 3],['item 4', 4],['item 5', 5],['item 6', 6],['item 7', 7],['item 8', 8],['item 9', 9]];
        alert(miArrayDeMetodo);
    })();

</script>
  

Remember that the manipulation to create the array is on the server side and every time you perform a PostBack your form will always invoke that static property and method.

    
answered by 23.02.2017 в 20:18