Code Monkey home page Code Monkey logo

chart.mvc's Introduction

Chart.Mvc Nuget

A .NET wrapper for MVC 5 to generate charts using the popular Chart.Js library (http://www.chartjs.org).

Sample

You can see the library in action here: http://www.martinobordin.it/Chart.Mvc

Complex chart Simple chart

Installation

Install using Nuget or compile binary from https://github.com/martinobordin/Chart.Mvc.git.

    PM> Install-Package Chart.Mvc

How do I use it?

To use the library you just need to:

  • include a reference to Chart.Js library (provided in Nuget Package or downloadable from http://www.chartjs.org, )

  • insert a canvas in your HTML

  • call the method Html.CreateChart(), passing the canvas name and the chart object you want to use

      @{
          var barChart = new BarChart();
          barChart.ComplexData.Labels.AddRange(new []{ "January", "February",  "March", "April", "May", "June", "July"});
          barChart.ComplexData.Datasets.AddRange(new List<ComplexDataset>
                                 { 
                                    new ComplexDataset
                                        {
                                            Data = new List<double> { 65, 59, 80, 81, 56, 55, 40 },
                                            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)",
                                        }, 
                                    new ComplexDataset
                                        {
                                            Data = new List<double> { 28, 48, 40, 19, 86, 27, 90 },
                                            Label = "My Second dataset",
                                            FillColor = "rgba(151,187,205,0.2)",
                                            StrokeColor = "rgba(151,187,205,1)",
                                            PointColor = "rgba(151,187,205,1)",
                                            PointStrokeColor = "#fff",
                                            PointHighlightFill = "#fff",
                                            PointHighlightStroke = "rgba(151,187,205,1)",
                                        }
                                });
      }
      
      <canvas id="myCanvas" width="400" height="400"></canvas>
      @Html.CreateChart("myCanvas", barChart)
    

Note:

  • Be sure to call CreateChart AFTER the reference to Chart.js file
  • The generated chart object will be named like the canvas plus "_chart" suffix (for the example above: myCanvas_chart). In this way you can attach handlers and call method like generateLegend().

The chart object contains information like chart type, labels, data and visualization options. Property names are the same of the original Chart.Js, so it should be easy to use them.

Currently all the 6 types of Charts.Js charts are supported and fully configurable:

  • Line chart (BarChart class with BarChartOptions)
  • Bar chart (LineChart class with LineChartOptions)
  • Radar chart (RadarChart class with RadarChartOptions)
  • Polar area chart (PolarAreaChart class with PolarAreaChartOptions)
  • Pie charts (PieChart class with PieChartOptions)
  • Doughnut charts (DoughnutChart class with DoughnutChartOptions)

Disclaimer

The software is provided "AS IS". I didn't full test it (Chart.Js has tons of options) and you'd need to properly escape strings containing JavaScript and be sure to pass correct parameters (valid colors values, etc) .

To contribute and improve the code just contact me!

chart.mvc's People

Contributors

martinobordin avatar sudmanche avatar waffle-iron avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chart.mvc's Issues

Issue forking project , missing project error

I dont know if this is an issue, but I tried to fork the last release version and there is a lot of deletes file.

Only the sample project is available.

I checkout two commits before and I have the "right" data.

I am looking for adding a title for the chart.

Support for ASP.NET Core

Hi,

I'm very interested in your solution for my current project. This will be developed in ASP.NET Core 1.0 with a modularized structure. Currently your solution contains some parts for Mvc6. Are there any plans to port this for ASP.NET Core inclusive missing options from Chart.Mvc like colors? Currently I'm missing some points for evaluation:

  • Your Chart.Mvc6 uses netcoreapp1.0. This could be changed to netstandard(1.6) for integration in .NET Core libraries as well.
  • A standalone publish to nuget for easily integration in ASP.NET Core solutions.

Thanks and Regards
Thomas

Struggling with dynamic data

Hi, I am try to create a graph but having problems converting the data to a format compatible with Chart JS. I'd like a graph like the one below.

image

The Data returned from SQL looks like this.

image

This data will dynamically change so I can't manually create the datasets. The data should be dynamically generated from the database.

White, clean sheet.

  1. PM> Install-Package Chart.Mvc.
  2. Inserted into View all the code entirely from the example:

@{Layout = null;}
@using Chart.Mvc.ComplexChart;
@using Chart.Mvc.Extensions
@....
...

@Html.CreateChart("myCanvas", barChart)

  1. Run...:

An unhandled exception on line 16, column 801 to http: // localhost: 62329 / Home / ComplexCharts
0x800a1391 - JavaScript Runtime Error: "Chart" is not defined

...var myCanvas_chart = new Chart(ctx).Bar(data, options)...

I got a white blank sheet. What's wrong?

Why is ScaleLabel commented out?

I see a commented out ScaleLabel in GlobalChartOptions.cs. I forked it, added back in and it ran fine. Is there any reason why it was left out?

Unable to access specific chart options from ChartConfiguration

Because the ChartConfiguration of a chart is either SimpleChartOptions or ComplexChartOptions (and not the underlying options of the chart itself) I am unable to access particular settings. For example a DoughnutChart has PercentageInnerCutout in DoughnutChartOptions (which inherits SimpleChartOptions). I am unable to set that setting to anything other than its default. This is the same for any options specific to a chart.

SyntaxError: unterminated string literal

In Chrome : Uncaught SyntaxError: Unexpected token ILLEGAL and in Firefox : SyntaxError: unterminated string literal - i added reference to chartjs before @Html.CreateChart("myCanvas", barChart). also trying with provided sample code in repository.

unable to generate legend

Thx for Chart.Mvc, really like to be able to use this in MVC. Could you post a simple example on how to show legend. Much appreciated it.

horizontalBar

Ciao Martino,
ti chiedo se hai idea di implementare il tipo 'horizontalBar', che mi pare manchi.
Hi Martino,
I'm wondering if you're planning to add the 'horizontalBar' type, which is currently missing.

Turning On Legends

There is someway to just set the legends to "On", or something like display = true ??
Im looking around in your code but no success till now. I would rather do by the code instead of get the same element again in javascript and turn it.

Getting an error with the latest version of MVC.

Assuming assembly reference 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' used by 'Chart.Mvc' matches identity 'System.Web.Mvc, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' of 'System.Web.Mvc', you may need to supply runtime policy DAN Report Screens V2 C:\Users\smorgan\Source\repos\DAN Report Screens V2\DAN Report Screens V2\Views\Mscc\Test.cshtml 43 Active

Facing issue to load chart

Hi,
I am trying to implement charts in MVC4. Following error get thrown at runtime

image

This line of code get generated in dll which is giving error
image


I have seen following difference in extension file.

  1. In sample file Extension.cs file has following code in bold which works file.
    private static MvcHtmlString CreateChart(string canvasId, string chartType, string jsonData, string jsonOptions)
    {
    var tag = new TagBuilder("script");
    tag.Attributes.Add("type", "text/javascript");
    var stringBuilder = new StringBuilder();
    stringBuilder.AppendFormat("var ctx = document.getElementById("{0}").getContext("2d");", canvasId);
    stringBuilder.AppendFormat("var data = JSON.parse('{0}');", jsonData);
    stringBuilder.AppendFormat("var options = JSON.parse('{0}');", jsonOptions);
    stringBuilder.Append("var " + canvasId + "_chart = new Chart(ctx, { type:'" + chartType.ToCamelCase() + "', data: data, options: options });");
    tag.InnerHtml = stringBuilder.ToString();
    return new MvcHtmlString(tag.ToString());
    }

  2. But in downloaded nuget package extension dll has following code which gives error.
    image

Could you please update nuget package?

Error in Javascript

I am getting an error with in the javascript. here is the code from your example...

@{
ViewBag.Title = "Chart";
}

ChartTest

@using Chart.Mvc.ComplexChart;
@{
var barChart = new BarChart();
barChart.ComplexData.Labels.AddRange(new[] { "January", "February", "March", "April", "May", "June", "July" });
barChart.ComplexData.Datasets.AddRange(new List
{
new ComplexDataset
{
Data = new List { 65, 59, 80, 81, 56, 55, 40 },
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)",
},
new ComplexDataset
{
Data = new List { 28, 48, 40, 19, 86, 27, 90 },
Label = "My Second dataset",
FillColor = "rgba(151,187,205,0.2)",
StrokeColor = "rgba(151,187,205,1)",
PointColor = "rgba(151,187,205,1)",
PointStrokeColor = "#fff",
PointHighlightFill = "#fff",
PointHighlightStroke = "rgba(151,187,205,1)",
}
});
}

@using Chart.Mvc.Extensions;

@Html.CreateChart("myCanvas", barChart)

capture

Chart.Mvc namespace issue on razor page

image20150402_003

It seems namespace conflict with System.Web.Helpers.Chart and Chart.Mvc on razor page

I have to change the namespace to ChartJs.Mvc and recomplie the project to make my mvc project work. (my project is built in .NET Framework 4.5)

Allowing null elements in ComplexDataSet.Data

Currently this property is a List, whereas Chart.JS allows null values to represent gaps in data (e.g. an x-axis of dates where data for some days are missing). Could ComplexDataSet.Data change to a List<double?> to support this case please?

prefix/suffix of labels

How would I prefix/suffix y-axis labels?
In JS it would be something like

var options = {
            scaleLabel: function(valuePayload) {
                return "  " + Number(valuePayload.value + ' TB';
            }

BarChart() , ComplexDataset and Html.CreateChart not found

Apologies if being stupid here, fairly new to MVC with views...

I installed your wrapper to project in VS2017 from nuget manager.
I see you include chart.js so didn't add that as well (also tried installing Chart.js package as well with same result).

I have added bundle for the Chart.js and include in HEAD of cshtml. Added bundle to the BundleConfig
@Scripts.Render("~/bundles/ChartJS")

I dragged in sample code from your "how do I use it?" section on site.

VS is telling me new BarChart() type or namespace not found
VS is telling me ComplexDataset type or namespace not found
VS is telling me @Html.CreateChart htmlHelper does not have a definition for CreateChart

Project is ASP.NET mvc against .net framework 4.6.1
Dependencies are later than required in your nuget description

I do have
using System.Web.Helpers

I can see Chart.Mvc in project references

I did implement a view with Microsoft's built in Chart but trying Chart.js as appears more feature rich and (thought) easier to implement.

I tried adding below but VS says unnecessary
using Chart.Mvc

re-read documentation and tried multiple remove/installs/project clean etc but can't get past this.

ChartConfiguration not implemented

Setting anything through ChartConfiguration does not feed through to the page.

it is due to the ChartConfiguration returning a new xxxChartOption();

I will look to provide a fix.

Type Clash between System.Web.Helpers.Chart and Chart.Mvc

I installed Chart.Mvc and tried to use in a Razor View from my project. The Instellisense and IIS returned me the following error:

CS0426: Name type 'Mvc' does not exist in type 'System.Web.Helpers.Chart'

System.Web.Helpers.Chart comes from Microsoft.AspNet.WebPages package. I can't remove this package from my application because other Views use this package.

LegendTemplate

I can't get the legend template to work in a LineChart. The default legend template doesn't work, but even a simple legend like

<ul><li>Epocalypse</li><li>Tiefdaas</li><li>Niels</li><li>Ivar</li><li>Jan Vis</li><li>Geerd</li><li>G. Saadfeit</li><li>Saadfeit</li><li>Lijst 1</li><li>Bas</li></ul>

Is not working. What am I missing?

Problem with Html.CreateChart

knipsel

This is the error: HtmlHelper<PMSensorDetail>' does not contain a definition for 'CreateChart' and no extension method 'CreateChart' accepting a first argument of type 'HtmlHelper<PMSensorDetail>' could be found (are you missing a using directive or an assembly reference?)

Does somebody have an idea?

Chart-Options are Ignored

Hello,

If I do this:

var barChart = new BarChart(); barChart.ChartConfiguration.ScaleBeginAtZero = true; barChart.ChartConfiguration.ScaleOverride = true; barChart.ChartConfiguration.MaintainAspectRatio = false;

The Scale doesnt begin by Zero. It begins with nearly the smallest of all the values which is practically really a questionable way of using charts. I'm headed over to the chart.js people to ask why thats the default.

But for now, the option isnt applied. I have to insert a Value of 0 for having an invisible column that makes the chart start at 0. Since that makes all the actually visible bars move to the left, its not that well of a problem solve, too, because now theres a blank space next to all of them all the time, like in the attached item.

blank_space

Issue with overriding scaling

lineChartBottom.ChartConfiguration.ScaleBeginAtZero = true;
lineChartBottom.ChartConfiguration.ScaleOverride = true;
lineChartBottom.ChartConfiguration.ScaleStartValue = 300;
lineChartBottom.ChartConfiguration.ScaleSteps = 5;

The scaling basically starts at 300, each 5 steps show the value of 300.

Any suggestions would be appreciated.

show value above bars using asp.net mvc

hi
how can i use constent values in each of above bars like title which must be hovered that.
i am using asp.net mvc 5 and my code that is used is

` @{
var globalbarChart = new BarChart();
globalbarChart.ComplexData.Labels.AddRange(Model.Select(d => ShamsiDate.ChangeDate(d.Date_Submitted).ToString()).ToList());

    globalbarChart.ComplexData.Datasets.AddRange(new List<ComplexDataset>
        {
            new ComplexDataset
            {
                Data =Model.Select(r=>double.Parse(r.Global_Rank.ToString())).ToList(),
                Label = "My First dataset",
                FillColor = "rgba(255,255,0,0.3)",
                StrokeColor = "rgba(255,0,255,0.3)",
                PointColor = "rgba(220,220,220,1)",
                PointStrokeColor = "#fff",
                PointHighlightFill = "#fff",
                PointHighlightStroke = "rgba(220,220,220,1)",

           }
                      });

}
<canvas id="globalCanvas" width="500" height="300"></canvas>`

ComplexDataset.Label property not showed

Hi Martino,
why Label property doesn't show the text ("Data1") but empty string ?
This is the code:
new ComplexDataset
{
Data = Datalist1,
Label = "Data1",
FillColor = "rgba(255, 206, 86, 0.2)",
StrokeColor = "rgba(220,220,220,1)",
PointColor = "rgba(220,220,220,1)",
PointStrokeColor = "#fff",
PointHighlightFill = "#fff",
PointHighlightStroke = "rgba(220,220,220,1)",

Thanks in advance

Readme corrections

Hi Martino,

This is a very useful wrapper, thumbs up! I would only suggest you to correct one small mistake and add one information to your readme file:

  • instead of ComplextDataset it should be ComplexDataset
  • in the current version Chart.js must be included before the @Html.CreateChart call (perhaps it would be wise to use another js event so that Chart.js could be loaded at the end of the view)

Kind regards,
Tomaz

GenerateLegend

Hi Martino,

I can't figure out how to show a legend with Chart.Mvc - I noted in the Chart.js documentation "generateLegend" can be used. Can you please advise, thank you.

Kind regards,
Tomaz

CreateChart is not working.

2016-10-21_17-08-57
I get this error:

'IHtmlHelper' does not contain a definition for 'CreateChart' and the best extension method overload 'HtmlExtensions.CreateChart(HtmlHelper, string, ComplexChartBase)' requires a receiver of type 'HtmlHelper'

I am running from an asp.net core project using .NET 4.5.2. Using version 1.0.0.2 of Chart.Mvc and I've tried using chart.js version 2.0.2 and 1.0.1. Both gave me the same error.

I have included the chart.js reference like in the example in _Layout.cshtml: <script src="~/lib/chartjs/Chart.bundle.js"></script>

It seems like there is an overload missing? But more likely, I am missing something.

Unfortunately the object browser does not work well for this project type, but I do have the extensions included.

Bar highlight on hover

In a barchart, highlighting of the bars on mousehover doesn't seem to be configurable. Chart.js has two properties for this, namely highlightFill and highlightStroke.

need help with generateLegend()

Hello,
I'm trying to display label/legend. In LineChart.cshtml, I added generateLegend() like so:


@{
const string Canvas = "LineChart";
var complexChart = new LineChart();
complexChart.ComplexData.Labels.AddRange(FakeComplexChartDataLineChart.Labels);
complexChart.ComplexData.Datasets.AddRange(FakeComplexChartDataLineChart.Datasets);
}

@canvas

@Html.CreateChart(Canvas, complexChart) Canvas_chart.generateLegend(); - - - -

But still don't see the legend. Can you correct my syntax?

Followed QuickStart guide, javascript error "Chart" undefined occurs

Hello,

I'm a newbie to webstuff overall. I followed the things listed under QuickStart guide.

This is how my View looks like:

`@model WebProto.Models.Movie
@using Chart.Mvc.ComplexChart;
@using Chart.Mvc.Extensions;
@{
ViewBag.Title = "Movie-Chart";
Layout = "~/Views/Shared/_Layout.cshtml";
}

@Model.Name

@{
var barChart = new BarChart();
barChart.ComplexData.Labels.AddRange(new[] { "January", "February", "March", "April", "May", "June", "July" });
barChart.ComplexData.Datasets.AddRange(new List
{
new ComplexDataset
{
Data = new List { 65, 59, 80, 81, 56, 55, 40 },
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)",
},
new ComplexDataset
{
Data = new List { 28, 48, 40, 19, 86, 27, 90 },
Label = "My Second dataset",
FillColor = "rgba(151,187,205,0.2)",
StrokeColor = "rgba(151,187,205,1)",
PointColor = "rgba(151,187,205,1)",
PointStrokeColor = "#fff",
PointHighlightFill = "#fff",
PointHighlightStroke = "rgba(151,187,205,1)",
}
});
}


@Html.CreateChart("myCanvas", barChart)`

When the very last line of it is executed I get Runtime Error in JavaScript "Chart" is undefined.

It then shows me this dynamic dump of the generated file And it marks the last line of this:

var myCanvas_chart = new Chart(ctx).Bar(data, options)

How do I add the correct reference to the generated javascript block?

Hide legend

How to hide a legend? I cannot see this in the chart options?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.