Nilmini Kiriwandala
Nilmini Kiriwandala

Reputation: 15

MVC3 gives a Blank chart

My LoggedUserHome.Controller has this action for chart

 public ActionResult GetGender()
    {


        var AllGender = new List<string>(from c in db.tbl_Profile select c.sex).ToList();
        var Groping = AllGender
           .GroupBy(i => i)
           .Select(i => new { sex = i.Key, CountGet = i.Count() }).ToArray(); //get a count for each

        var key = new Chart(width: 300, height: 300)
            .AddSeries(
            chartType: "pie",
            legend: "Gender Popularity",
            xValue: Groping, xField: "sex",
            yValues: Groping, yFields: "CountGet")
            .Write("gif");
        return null;

    }

and in my view I have given

<img src="/LoggedUserHome/GetGender"/>

Thanks to Nexuss ToArray() suggestion I manage to populate the chart by reading the database.. Thanks a lot Nexuzz

Upvotes: 1

Views: 540

Answers (1)

nexuzzz
nexuzzz

Reputation: 238

Simple solution is to try to replace your

<img src="/LoggedUserHome/GetGender"/>

in the view with

@{
    var d = new PrimeTrekkerEntities1();
    var AllGender = new List<string>(from c in d.tbl_Profile select c.sex).ToList();
    var Groping = AllGender
        .GroupBy(i => i)
        .Select(i => new { sex = i.Key, Count = i.Count() }); //get a count for each

    var key = new Chart(width: 600, height: 400)
        .AddSeries(
        chartType: "pie",
        legend: "Gender Popularity",
        xValue: Groping, xField: "sex")
        .Write("gif");
}

And "yes" you don't need action GetGender in this case.

More complex solution would be to leave

<img src="/LoggedUserHome/GetGender"/>

in the view, but make GetGender() action return chart image URL. So, what you can do in GetGender() is somehow render chart into image file and return response that contains the image's path.

update:

I've updated your example a bit, so it displays data in the chart. Here is what I've got:

@{
    var AllGender = new List<string>() { "Male", "Female", "Male"};
    var Groping = AllGender
        .GroupBy(i => i)
        .Select(i => new { sex = i.Key, Count = i.Count() }).ToArray(); //get a count for each

    var key = new Chart(width: 600, height: 400)
        .AddSeries(
        chartType: "pie",
        legend: "Gender Popularity",
        xValue: Groping, xField: "sex",
        yValues: Groping, yFields: "count")
        .Write("gif");
}

There are two main differences with your example:

  • Groping is now an array. As far as I understand Chart expects data to be enumerated
  • I added yValues and yFields parameters, so chart knows what values to use on Y axis

Upvotes: 1

Related Questions