How to use Chart.Js with ASP.NET MVC

Asked

Viewed 2,474 times

2

Well, I’m returning a list of and sending to View. And I need to implement this through a chart with Chart.js.

I have the class Parents:

[Table("Pais")]
public class Pais
{
    [Key]
    public Guid PaisId { get; set; }

    [Required]
    public String Nome { get; set; }

    public virtual ICollection<FertilidadePorAno> FertilidadePorAno { get; set; }
}

The class Fertility:

[Table("FertilidadePorAno")]
public class FertilidadePorAno
{
    [Key]
    public Guid FertilidadePorAnoId { get; set; }
    public Guid PaisId { get; set; }

    [Required]
    public int Ano { get; set; }

    [Required]
    public decimal Valor { get; set; }

    public virtual Pais Pais { get; set; }
}

And an associative class Paisfertilidadeporano:

[Table("PaisFertilidadePorAno")]
public class PaisFertilidadePorAno
{
   public Guid PaisFertilidadePorAnoId { get; set; }

    public string  Nome { get; set; }

    public int Ano { get; set; }

    public double Valor { get; set; }
}

Man controller that searches the data in the Bank:

 public async Task<ActionResult> Relatorio(Guid id)
 {
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    var entries = db.Database.Connection
   .Query<PaisFertilidadePorAno>(@"SELECT p.Nome, f.Ano, f.Valor from Pais As p
                                                    inner join FertilidadePorAno as f
                                                    on f.PaisId = p.PaisId
                                                    where p.PaisId = @id
                                                    order by f.Ano", new {  Ano = (int?)null, Id = id });
        return View(entries);
    }

Return the data to the View which is currently like this:

@model IEnumerable<TaxaDeFertilidade.Models.PaisFertilidadePorAno>

@{
    ViewBag.Title = "Relatorio";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Relatorio</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Nome)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Ano)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Valor)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Nome)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Ano)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Valor)
        </td>
    </tr>
}

</table>

However, I need to create a chart chart.js with this information coming from the Bank which is the name of the Parents, Year and the Fertility Rate concerning that year. How do I do it in View?

2 answers

4


One simple way to use is by using the Chart.Mvc.

To use this package, simply install via Nuget with the following command:

Install-Package Chart.Mvc

After that, do something like this in your View:

@using Chart.Mvc.ComplexChart;
@using Chart.Mvc.Extensions

<script src="~/Scripts/Chart.js"></script>

@{
    ViewBag.Title = "Home Page";

    var nome = new[] { "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho" };
    var valores = new List<double> { 65, 59, 80, 81, 56, 55, 40 };

    var barChart = new BarChart();
    barChart.ComplexData.Labels.AddRange(nome);

    barChart.ComplexData.Datasets.AddRange(new List<ComplexDataset>
                           {
                              new ComplexDataset
                                  {
                                      Data = valores,
                                      Label = "My First dataset",
                                      FillColor = "rgba(220,220,220,0.2)",
                                      StrokeColor = "rgba(220,220,220,1)",
                                      PointColor = "rgba(220,220,220,1)",
                                      PointStrokeColor = "#fff",
                                      PointHighlightFill = "#fff",
                                      PointHighlightStroke = "rgba(220,220,220,1)",
                                  }
                          });
}

<canvas id="myCanvas" width="400" height="400"></canvas>
@Html.CreateChart("myCanvas", barChart)

Just change the variables name and values for the values you want.

The result will be this:

inserir a descrição da imagem aqui

  • I wouldn’t put code c# in the view like this.

  • 1

    @Marcoviniciussoaresdalalba The C# code you have is to simulate the values it already has on Model. The barChart it can create in Controller and forward to View, but it would be more complex to explain the operation based on its question. And the Html.CreateChart is a HtmlHelper which is widely used in Asp.Net MVC. But I agree with you, it’s not cool to mix the codes.

  • @Randrade, you’ve met my need.

1

I would advise you to implement your method as Jsonresult and take the data from Json and process it in your Chart.js in the view, according to this dotnetfiddle example.

https://dotnetfiddle.net/h6lJUN

I hope I’ve helped ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.