display charts using MVC, .net c# - c#

I'm trying to display some charts on my mvc app but I'm having some errors. I'm developing in localhost. I have one cshtml file named ReportChart
#{
var myChart = new Chart(width: 600, height: 400)
.AddTitle("Chart Title")
.AddSeries(
name: "Employee",
xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" },
yValues: new[] { "2", "6", "4", "5", "3" })
.Write();
}
and another file that use that chart:
<body>
<h1>Chart Example</h1>
<p>The following chart is generated by the <em>ReportChart.cshtml</em> file:</p>
<p><img src="ReportChart.cshtml" alt="Cricketers" /> </p>
The only problem is that the webpage doesn't display any image :/

No it won't work in MVC. You should create chart in the controller action method:
//I CUT THE CODE WHERE I construct string[] t1 and int[] t2 these are just arrays
public ActionResult EfficiencyChart(string pid) {
var myChart = new Chart(width: 1000, height: 600)
.AddTitle("Employee's Efficiency")
.AddSeries(
name: "Employee",
xValue: t2,
yValues: t1)
.Write();
myChart.Save("~/Content/chart" + user.Id, "jpeg");
// Return the contents of the Stream to the client
return base.File("~/Content/chart" + user.Id, "jpeg");
}
Then in the Razor view:
<img src="#Url.Action("EfficiencyChart", "NAME_OF_THE_CONTROLLER", new { pid = #Model.Id })" />

try it,
<p><img src="#Url.Action("ReportChart")" alt="Cricketers" /> </p>
public ActionResult ReportChart()
{
return PartialView();
}

Related

How to send byte array as paramater to HTML.Action?

I have been working with charts today And I think that i finaly found a way for it all to work but I encountered an issue that I don't know how to pass.
Create my Charts in my controller:
foreach (var m in model[0].HistoryValues)
{
var chart = new Chart(width: 300, height: 200)
.AddSeries(
chartType: "bar",
xValue: new[] { "Server", "Db", "Tickets" },
yValues: new[] { m.ServerPerformance, m.Databaseperformance, m.SoldTicketsLastUpdate })
.GetBytes("png");
m.Bytes = chart;
//m.ChartFile = File(chart, "image/bytes");
};
now I want to display them as Images in the view:
#foreach (var m in Model[0].HistoryValues)
{
<img src="#Html.Action("getImage", "OverWatch", new { byte[] Mybytes= m.Bytes })" alt="Person Image" />
}
but im getting:
Invalid anonymous type member declarator. Anonymous type members must
be declared with a member assignment, simple name or member access.
getImage method:
public FileContentResult getImage(byte[] bytes)
{
return new FileContentResult(bytes, "image/jpeg");
}
How do I solve this?
In an anonymous type you dont define the variable type byte[]. It works it out itself based on the type of m.Bytes
#foreach (var m in Model[0].HistoryValues)
{
<img src="#Html.Action("getImage", "OverWatch", new { Mybytes= m.Bytes })" alt="Person Image" />
}

Embedding a pie chart in ASP.NET (Razor syntax)

I'm fairly new to ASP.NET (have been coding in WPF a long time, but new to ASP) and I'm trying to create a dashboard application that shows four pie charts. I've followed the instructions on this link, but I either get a chart on the entire page, or a broken image (as if the <img> source is not valid)
Can someone please explain to me how to achieve this behavior? I just want to display a simple pie chart on my page, that's it.
Thanks! (and sorry if this is a duplicated post, I've found other similar questions but none using the Razor syntax)
EDIT - Here's my code:
Index.cshtml:
<!DOCTYPE html>
<html>
<head>
<title>Chart Example</title>
</head>
<body>
<h1>Chart Example</h1>
<p>
The following chart is generated by the <em>ChartView.cshtml</em> file, but is shown
in this page.
</p>
<p><img src="ChartView.cshtml" /> </p>
</body>
</html>
My ChartView.cshtml: (located in the same folder as Index.cshtml)
#{
var myChart = new Chart(600, 400)
.AddTitle("Employees")
.AddSeries(chartType: "column",
xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" },
yValues: new[] { "2", "6", "4", "5", "3" });
if (myChart != null)
{
myChart.Write();
}
}
This is what I get on the browser:
You can't return a .cshtml file (unless you fiddle dangerously with various internal settings - not recommended).
You should be pointing to an action.
The easiest way to test this is by opening the src directly in the browser - in this case "ChartView.cshtml" and you should get a 404.
You'll need to add an action to your controller that returns the view.
public HomeController : Controller
{
public ActionResult ChartView()
{
return View();
}
then
<img src='#Url.Action("ChartView", "Home")' alt="Chart"/>
You can test this by opening in the browser:
/Home/ChartView
(this assumes that ChartView.cshtml is in the folder "Views/Home")
As you're new to MVC, quick explanation. There a 'routeConfig.cs' which routes incoming urls to an action(method) on a controller(class). The controller loads the view (cshtml) and applies all the server-side code then returns the rendered html to the user.
You do not navigate directly to cshtml pages but navigate instead to actions via the url.
The default route config gives you urls such as:
http://[site]/[controller]/[action]
Note that [controller] does not include "Controller", so "HomeController" becomes "/Home/"
Also, by convention, if you don't specify a view name in 'View()' then it will look in your solution folder "/Views/[controller]/[action].cshml' (among other locations such as '/Views/Shared/[action].cshtml' (also configurable, but these are the defaults).
you easely can combine
http://morrisjs.github.io/morris.js/index.html
in mvc (razor syntax)
or you can use chart helper
http://www.asp.net/web-pages/overview/data/7-displaying-data-in-a-chart
change to:
#{
var myChart = new Chart(600, 400)
.AddTitle("Employees")
.AddSeries("SomeName",chartType: "Pie",
xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" },
yValues: new[] { "2", "6", "4", "5", "3" });
if (myChart != null)
{
myChart.Write();
}
}
you have to lunch it in iis or some development server

JQGrid in MVC Not Loading the Grid

I have an MVC Edit View that contains Contact Information that is of course editable. In that view I want to add a section containing a JQGrid allowing the user to CRUD notes for the Contact but my grid is not loading with data nor is the method on the controller being called. Can anyone give me any insite?
View Code
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-info">
Contact Note</h3>
</div>
<div class="panel-body">
<div class="scrollableContainer" style="margin-top: -10px;">
<table id="JQGrid1"></table>
<div id="JQGrid1_pager"></div>
</div>
</div>
</div>
<script>
$("#JQGrid1").jqGrid({
url: '#Url.Action("GetNotes", "Contact")',
mtype: "GET",
datatype: "json",
page: 1,
jsonReader: { id: document.getElementById('SelectedContact_ContactID').value },
prmNames: { id: document.getElementById('SelectedContact_ContactID').value },
colNames: ["Id", "ContactId", "Note", "Date Created", "Created By"],
colModel: [
{ key: true, width: 50, name: "ID", hidden: false },
{ width: 60, name: "ContactID", hidden: false },
{ width: 460, name: "Note", hidden: false },
{ width: 160, name: "DateCreated",
formatter: "date", formatoptions: { srcformat: "m/d/Y h:i:s A", newformat: "mm-dd-yyyy" }, hidden: false },
{ width: 160, name: "CreatedBy", hidden: false },
],
height: "auto",
caption: "Notes",
rowNum: 5,
pager: "#JQGrid1_pager",
});
</script>
Controller Code
[HttpGet]
public JsonResult GetNotes(int id)
{
var gridModel = new ContactNotesJQGridModel();
var resultset = _contactNoteRepository.GetNotes(id);
return gridModel.ContactNotesGrid.DataBind(resultset.AsQueryable());
}
GridModel Class
public class ContactNotesJQGridModel
{
public JQGrid ContactNotesGrid { get; set; }
public ContactNotesJQGridModel()
{
ContactNotesGrid = new JQGrid
{
Columns = new List<JQGridColumn>()
{
new JQGridColumn {DataField = "ID", PrimaryKey = true},
new JQGridColumn {DataField = "ContactId"},
new JQGridColumn {DataField = "Note"},
new JQGridColumn {DataField = "DateCreated"},
new JQGridColumn {DataField = "CreatedBy"},
}
};
}
Then in the Edit Call for the Contact in the Contact Controller I set model.ContactNotesGrid = new ContactNotesJQGridModel GetNotes(int id) is never executed eventhough it's specified in the jquery.
You should use postData to add custom parameter to the server response:
postData: { id: 11 }
or
postData: {
id: function () {
return document.getElementById('SelectedContact_ContactID').value;
}
}
You need additionally modify the code of the server to use something like
return Json(someObjectWithReturnedData, JsonRequestBehavior.AllowGet);
I recommend you to add loadError callback to the list of jqGrid option (see the answer) and add gridview: true and autoencode: true option to jqGrid.
P.S. About the errors like "unable to get value of the property integer", "unable to get value of the property decimalSeperator". You should verify that you included locale file like i18n/grid.locale-en.js before jquery.jqGrid.min.js (see the documentation).
Try this :
Check 1:
Move your Jquery script inside the document ready event:
$( document ).ready(function() {
console.log( "ready!" );
});
Check 2:
Check weather your server request having any problem or not:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
}
Add the above code in your Global.asax and make sure there is no exception during the call. (Put Break point and check)
Check 3:
Watch your browser console log (F12). If there is any exception log please provide that.
Check 4:
Make sure if the call is success the expected json format is valid or not. In most of the cases it will be the major cause.
The above's are just my guesses / this is what i do first, if i have a prob. :)

Uncaught TypeError: undefined is not a function - Highcharts - MVC

I'm trying to use Highcharts in my MVC web application. I have loaded all the prerequisites to make Highcharts working. But apparently, "highchart" is still not recognized by the page. I'm checking the rendered page by google developer tool and it says all the JQuery and Highchart javascript files are loaded properly. Any help?
This is my .cshtml code:
#using System.Web.Optimization
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/Highcharts-4.0.1/js/highcharts.js")
#Scripts.Render("~/Scripts/Highcharts-4.0.1/js/modules/exporting.js")
<script type="text/javascript">
$(function() {
var chart;
debugger;
$(document).ready(function() {
debugger;
// Build the chart
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2014'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
},
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}]
});
});
});
</script>
}
So this does the trick (which is kind of weird!) :
I need to change this line:
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
To this line:
chart = new Highcharts.Chart({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
renderTo: 'container'
},
This is the link which helped me through: http://developmentpassion.blogspot.com/2013/09/bar-charts-and-graphs-in-aspnet-mvc.html

Call controller from aspx

This is my first time trying to implement a project using MVC, and I am kind of lost.
I have a view, named chart.aspx
and a controller which has the function
public ActionResult GetChartImage()
{
var key = new Chart(width: 300, height: 300)
.AddTitle("Employee Chart")
.AddSeries(
chartType: "Bubble",
name: "Employee",
xValue: new[] { "Peter", "Andrew", "Julie", "Dave" },
yValues: new[] { "2", "7", "5", "3" });
return File(key.ToWebImage().GetBytes(), "image/jpeg");
}
I want to call that from my aspx page, in order to show a chart.
How I can do that?
In your view add the following:
<img src="<%= Html.Action("GetChartImage", "YourControllerName") %>" />
Try this,Use Url.action in your img tag src
and also need to change ActionResult to FileContentResult . But it does not a matter .
<img src="#Url.Action("GetChartImage", "YourControllerName")" />

Categories