0

I have a code that I need to import a variable from C# to JavaScript.

Within JavaScript, the variable is of the Json type.

When I manually create the variable inside JavaScript, my function and graphics work perfectly, but when I tried to get data from a C# variable, it doesn't work, my variable is empty.

This variable works when I create inside JavaScript:

var providerChart = [{ date: "2020-07-27", value: 13 }, { date: "2020-07-28", value: 11 }, { date: "2020-07-29", value: 15 }, { date: "2020-07-30", value: 16 }, { date: "2020-07-31", value: 18 }, { date: "2020-08-01", value: 13 }, { date: "2020-08-02", value: 22 }, { date: "2020-08-03", value: 23 }, { date: "2020-08-04", value: 20 }, { date: "2020-08-05", value: 17 }, { date: "2020-08-06", value: 16 }];

When I try import from C#, it doesn't work

var providerChart = JSON.parse('<%=dash.DadosChart%>');

I used an alert(); to manage if the data arrived.

This is my controller, responsible to send my information to HTML and I have tried to use to send to JS too.

public IActionResult Index()
{
    ConsumeAPI consume = new ConsumeAPI();

    consume.ReceiveCookie();

    Dashboard dash = new Dashboard();

    //dash.DadosChart = new List<string[,]>();

    dash.QtdeAplicacoes = consume.ProjetosCadastrados("projects");
    dash.UltimaDataAplicacao = consume.ConvertDate(consume.UltimoProjeto("projects"));

    dash.QtdeProjetoAtivo = consume.ProjetosAtivos("projects", diasAtivo);
    dash.Atual = consume.ConvertDate(consume.UltimoUpdate);

    dash.QtdeUsuarioCadastrado = consume.UsuariosRegistrados("authEntities");
    dash.UltimaDataUsuario = consume.ConvertDate(DateTime.Today);

    dash.PercentualProjetoCritico = (float)MathF.Round(consume.PercProjetoCritico("projectVersions"), 2);
    dash.BarraPercentualProjetoCritico = (float)MathF.Round(dash.PercentualProjetoCritico, 0);
    dash.PercentualProjetoRemediacao = (float)MathF.Round(consume.PercProjetoRemedicao(), 2);
    dash.BarraPercentualProjetoRemediacao = (float)MathF.Round(dash.PercentualProjetoRemediacao, 0);
    dash.PercentualVulnerabilidadeRemediada = (float)MathF.Round(consume.PercVulnRemediada(), 2);
    dash.BarraPercentualVulnerabilidadeRemediada = (float)MathF.Round(dash.PercentualVulnerabilidadeRemediada, 0);
    dash.PercentualProjetoPausado = (float)MathF.Round(consume.PercProjetoPausado(), 2);
    dash.BarraPercentualProjetoPausado = (float)MathF.Round(dash.PercentualProjetoPausado, 0);
    dash.DadosChart = "[";
    for(int i = 0; i < consume.apps.Count; i++)
    {
        bool isFirst = true;
        string myDate = consume.apps[i].Criado.Year.ToString() + "/" + consume.apps[i].Criado.Month.ToString() + "/" + consume.apps[i].Criado.Day.ToString(); 
        int vulnTotal = (consume.vulnApps[i].TotalAlta + consume.vulnApps[i].TotalBaixa + consume.vulnApps[i].TotalCritica + consume.vulnApps[i].TotalMedia);
        if(isFirst){
            dash.DadosChart += "{date: " + myDate + ", value: " + vulnTotal + "}";
            isFirst = false;
        }else
        {
            dash.DadosChart += ",{date: " + myDate + ", value: " + vulnTotal + "}";
        }
        //int vulnTotal = (consume.vulnApps[i].TotalAlta + consume.vulnApps[i].TotalBaixa + consume.vulnApps[i].TotalCritica + consume.vulnApps[i].TotalMedia);
        //string[,] dado = { { "date", "value" }, { consume.apps[i].Criado.ToString(), vulnTotal.ToString() } };
        //dash.DadosChart.Add(dado);
    }
    dash.DadosChart += "]";

    //dash.MyDataChart = JObject.Parse(dash.DadosChart);
    

    return View(dash);
}

PS.: I have used ASP.Net Core 3.1

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • In JavaScript, there is no Json type. There is string, which is typically how JSON is transmitted (and the reason for the naming of the `JSON.stringify` method), and there is Object (or Array, or one of the other more specific types), which are stringified for transmission or parsed from a JSON string (via `JSON.parse`). – Heretic Monkey Mar 29 '21 at 14:05
  • First `[{ date:..` is not Json but javascript object [Ref](https://stackoverflow.com/questions/8294088/). Json has double quote around string "_A string is a sequence of zero or more Unicode characters, wrapped in double quotes,_" [ref](https://www.json.org/json-en.html). – Drag and Drop Mar 29 '21 at 14:07
  • 1
    The way to get data from a C# type to JavaScript is to serialize it as JSON; So `var providerChart = JSON.parse('<%=JsonConvert.Serialize(dash.DadosChart)%>');` if you have Newtonsoft.Json imported. – Heretic Monkey Mar 29 '21 at 14:09
  • 1
    Does this answer your question? [Asp.net mvc passing a C# object to Javascript](https://stackoverflow.com/questions/8145716/asp-net-mvc-passing-a-c-sharp-object-to-javascript) – Heretic Monkey Mar 29 '21 at 14:11
  • Or to simplify, Heretic's suggestion, just output it into the JS as if it was a hard-coded literal to begin with, then you don't need to parse it, e.g. `var providerChart = <%=JsonConvert.Serialize(dash.DadosChart)%>;` (This is ok because JSON syntax is a subset of JS object literal syntax.) – ADyson Mar 29 '21 at 14:25
  • @ADyson I have tried this before. I've thoght that error could be because I've used MVC model, so this .js is a individual arqchive and doesn't reconize my Newtonsoft.Json library. – douglas.silva Mar 29 '21 at 15:14
  • More precisely, I think you mean it doesn't execute the C# code in he `<%` brackets. Yeah this code as shown would need to be in a cshtml view file. Probably you need to run that in a view, and structure your .js code in such a way that there is a function your view's JS can call which passes the data to it, so it can then draw the chart. That way you can trigger the code from the view, and have the necessary data available. Either that or you could make the JS make an AJAX call to fetch the JSON directly from a separate action method on the server. It's up to you. – ADyson Mar 29 '21 at 15:17
  • 1
    @ADyson, you are corretly. I'm trying today to incluse the JS inside the cshtml and call the data via ViewBag. At the moment, it hasn't worked yet, but I'll continue keep trying. – douglas.silva Mar 30 '21 at 15:32

0 Answers0