I Used to Spring MVC. This is my Java Service
#Override
public ArrayList<SampleVO1> getAvgPetalBySpecies3() {
ArrayList<SampleVO1> irisList = new ArrayList<SampleVO1>();
try {
REXP result = rEngine.eval("(ming <- tapply(iris$Petal.Length, iris$Species, mean))");
REXP result1 = rEngine.eval("names(ming)");
SampleVO1 sample1 = new SampleVO1();
sample1.setName(result1.asStringArray());
sample1.setY(result.asDoubleArray());
irisList.add(sample1);
} catch (Exception e) {
logger.error(e.getMessage());
throw new RuntimeException(e);
}
return irisList;
}
Oh! This is my VO
private String[] name;
private double[] y;
And This is my Controller
#RequestMapping("/analytics/iris3")
public String getAvgPetalbySpecies3(Model model) {
ArrayList<SampleVO1> irisList = analyticsService.getAvgPetalBySpecies3();
Gson gson = new Gson();
String irisData = gson.toJson(irisList);
model.addAttribute("irisData2", irisData);
return "analytics/visual";
}
At Last, This my JSP
<script type="text/javascript">
$(function() {
Highcharts.chart('pie', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: ''
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true
},
showInLegend: true
}
},
series:
<%= request.getAttribute("irisData2") %>,
});
});
</script>
enter image description here
lol I saw White space...
and I checked my sourceCode!
series:
[{"name":["setosa","versicolor","virginica"],"y":[1.462,4.26,5.552]}],
I thought I receive not bad to iris data! but my highCharts didn't like that...
How I fixed My code...?
You currently have the following code to add values to your data.
SampleVO1 sample1 = new SampleVO1();
sample1.setName(result1.asStringArray());
sample1.setY(result.asDoubleArray());
irisList.add(sample1);
Where you set name = [] of strings, and Y = []ยด of Doubles.
This gives you [[name, name, name],[y,y,y]]
Instead you should either join or loop through the number of elements in your lists as follows:
for(int i = 1; i < result.length(); i = i + 1) {
SampleVO1 sample1 = new SampleVO1();
sample1.setName(result1[i].asStringArray());
sample1.setY(result[i].asDoubleArray());
irisList.add(sample1);
}
Which will give you a list like [[name, y], [name, y], [name, y]].
I am sure there is much better ways to add two arrays together in java though.
Regardless, in the end you should en up with a JSON formatted list such as:
[{name: 'setosa', y: 1.462}, {name: 'versicolor', y: 4.26}]
Highcharts Series takes a JSON Object. You need to convert <%= request.getAttribute("irisData2") %> to a json object as below.
var irisData2_string = '<%= request.getAttribute("irisData2") %>';
var obj = JSON.parse(irisData2_string);
Thanks EveryOne!
I write my full code for pie-chart in highCharts!
First, I show My ValueObject!
public class SampleVO1 {
private String name;
private double y;
public String getName() {
return name;
}
public void setName(String resultList1) {
this.name = resultList1;
}
public double getY() {
return y;
}
public void setY(double resultList) {
this.y = resultList;
}
}
Second, My service!
#Service
public class AnalyticsService implements IAnalyticsService {
private static final Logger logger =
LoggerFactory.getLogger(AnalyticsService.class);
#Autowired
Rengine rEngine;
...
#Override
public ArrayList<SampleVO1> getAvgPetalBySpecies3() {
ArrayList<SampleVO1> irisList = new ArrayList<SampleVO1>();
try {
REXP result = rEngine.eval("(ming <- tapply(iris$Petal.Length, iris$Species, mean))");
REXP result1 = rEngine.eval("names(ming)");
double resultList[] = result.asDoubleArray();
String resultList1[] = result1.asStringArray();
for(int i=0; i<resultList.length; i++) {
SampleVO1 sample1 = new SampleVO1();
sample1.setName(resultList1[i]);
sample1.setY(resultList[i]);
irisList.add(sample1);
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new RuntimeException(e);
}
return irisList;
}
Third, my Controller~
#Controller
public class AnalyticsController {
#Autowired
IAnalyticsService analyticsService;
#Autowired
IUploadFileService uploadFileService;
...
#RequestMapping("/analytics/iris3")
public String getAvgPetalbySpecies3(Model model) {
ArrayList<SampleVO1> irisList =
analyticsService.getAvgPetalBySpecies3();
Gson gson = new Gson();
String irisData = gson.toJson(irisList);
model.addAttribute("irisData2", irisData);
return "analytics/visual";
}
At last, My visualizing jsp!
<script type="text/javascript">
$(function() {
Highcharts.chart('pie', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'pie is ApplePie'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true
},
showInLegend: true
}
},
series: [{name: 'Species',
colorByPoint : true,
data :<%= request.getAttribute("irisData2") %>
}]
});
});
</script>
I hope these codes help you editing your highCharts!
Related
I want to input JSON data that I have from Database to highchart. but the chart didn't show up but JSON data does.
In ajax I already separate the category and data, but it's not working. especially because i don't know how to debug this javascript code. when I open inspect the sources in browser but it show nothing. I hope someone can help me
my ViewModel
public class DataByYear
{
public int Total { get; set; }
public string year { get; set; }
}
this is my Provider
public List<DataByYear> GetDataByYear()
{
tesdbEntities entities = new tesdbEntities();
var data = entities.Database.SqlQuery<DataByYear>("exec DataByYear");
return data.ToList();
}
I use SP to get the data from database
My Controller
public ActionResult Index()
{
return View();
var penjualan = new PenjualanProvider();
var index = new List<DataByYear>();
index = penjualan.GetDataByYear();
return this.Json(index, JsonRequestBehavior.AllowGet);
}
and this is my JS
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Index")',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: true,
success: function (dataChart) {
var Xaxis = [];
var dataseries = [];
for (i = 0; i < DataByYear.length; i++) {
var items = DataByYear[i];
var XcategoreisItem = items.year;
var seriesData = items.Total;
Xaxis.push(XcategoreisItem);
dataseries.push(seriesData);
getchart(Xaxis, dataseries);
}
}
})
});
function getchart(Xaxis, dataseries) {
$('#data').highcharts({
chart: {
type: 'line',
zoomType: 'xy',
panning: true,
panKey: 'shift'
},
title: {
text: 'Profit From 2018'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '{y}%',
}
}
},
xAxis: {
categories: Xaxis
},
yAxis: {
title: {
text: 'Y axis text'
},
series: dataseries
}
});
};
Sorry for my English.
I have an enum and my grid display only numeric values. How can I work only with text variant of enum? This is quite a common problem, but I still have not found a suitable solution for me.
I will be glad to any help with this issue)
Index.cshtml
#{
ViewBag.Title = "Book List";
}
<script type="text/kendo" id="authorsTemplate">
<ul>
# for(var i = 0; i < Authors.length; i++){ #
<li>#: Authors[i].AuthorName #</li>
# } #
</ul>
</script>
<div id="grid"></div>
<script>
function authorsEditor(container, options) {
$('<input name="Authors">').appendTo(container)
.kendoMultiSelect({
dataValueField: "AuthorId",
dataTextField: "AuthorName",
dataSource: #Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewData["authors"]))
});
}
$("#grid").kendoGrid({
pageable: true,
toolbar: ["create"],
dataSource: {
pageSize: 3,
transport: {
read: {
url: "#Url.Action("Read", "Grid")",
type: "POST"
},
update: {
url: "#Url.Action("Update", "Grid")",
contentType: "application/json",
type: "POST"
},
create: {
url: "#Url.Action("Create", "Grid")",
contentType: "application/json",//hz nado li
type: "POST"
},
destroy: {
url: "#Url.Action("Destroy", "Grid")",
contentType: "application/json",//hz nado li
type: "POST"
},
parameterMap: function(options) {
return kendo.stringify(options);
}
},
schema: {
model: {
id: "BookId",
fields: {
AuthorName: { type: "string" }
}
}
}
},
editable: "inline",
columns: [
"BookName",
"Pages",
// { editor: GenreEditor, field: "Genre" },IEnumerable<Number2.Models.AuthorViewModel>
"Genre",
"Publisher",
{
editor: authorsEditor, field: "Authors", template: $("#authorsTemplate").html()
},
{ command: ["edit", "destroy"] }
]
});
</script>
ViewModel and Enum(typical viewmodel and enum)
namespace Number2.Models
{
public class BookViewModel
{
public BookViewModel()
{
Authors = new List<AuthorViewModel>();
}
[ScaffoldColumn(false)]
public int BookId { get; set; }
[Display(Name = "Book Name")]
[MaxLength(100, ErrorMessage = "Book Name must be 100 characters or less"), MinLength(5)]
public string BookName { get; set; }
public int Pages { get; set; }
public string Publisher { get; set; }
[Range(0, maximum: 10)]
public Genre Genre { get; set; }
[UIHint("AuthorsEditor")]
public virtual List<AuthorViewModel> Authors { get; set; }
public void CopyToBook(Book book)
{
book.BookId = BookId;
book.BookName = BookName;
book.Pages = Pages;
book.Genre = Genre;
book.Publisher = Publisher;
}
}
public enum Genre
{
[Description("Comedy")]
Comedy,
[Description("Drama")]
Drama,
[Description("Horror")]
Horror,
[Description("Realism")]
Realism,
[Description("Romance")]
Romance,
[Description("Satire")]
Satire,
[Description("Tragedy")]
Tragedy,
[Description("Tragicomedy")]
Tragicomedy,
[Description("Fantasy")]
Fantasy,
[Description("Mythology")]
Mythology,
[Description("Adventure")]
Adventure,
}
}
Question is still relevant...
I think there is should use special viewmodel for my enum, but i dunno how can i do it correctly.
My view is displayed by external javascript instead of in the view itself. How do i delete multiple rows in jqgrid? I have the multiselect and multiboxonlyset equals to true. Here are my codes
View (the view is formatted in "~/Scripts/TodoList.js")
#{
ViewBag.Title = "Index";
}
<h2>TodoList</h2>
<div>
<table id="grid"></table>
<div id="pager"
</div>
<link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
Get Selected id's
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
#*<script src="~/Scripts/jquery-1.12.4.min.js" type ="text/javascript"></script>*#
<script src="~/Scripts/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="~/Scripts/TodoList.js" type="text/javascript"></script>
Todolist.js (Jqgrid)
/* File Created: February 17, 2017 */
$(function () {
$("#grid").jqGrid({
url: "/TodoList/GetTodoLists",
datatype: 'json',
mtype: 'Get',
colNames: ['Id', 'Task Name', 'Task Description', 'Target Date', 'Severity', 'Task Status'],
colModel: [
{ key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
{ key: false, name: 'TaskName', index: 'TaskName', editable: true },
{ key: false, name: 'TaskDescription', index: 'TaskDescription', editable: true },
{
key: false, name: 'TargetDate', id: "elem", index: 'TargetDate', editable: true, formatter: 'date', formatoptions: { newformat: 'd/m/Y' },
editoptions: { dataInit: function (elem) { $(elem).datepicker(); } }
},
{ key: false, name: 'Severity', index: 'Severity', editable: true, edittype: 'select', editoptions: { value: { 'L': 'Low', 'M': 'Medium', 'H': 'High'}} },
{ key: false, name: 'TaskStatus', index: 'TaskStatus', editable: true, edittype: 'select', editoptions: { value: { 'A': 'Active', 'I': 'InActive'}}}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30, 40],
height: '100%',
viewrecords: true,
// Bug Codes
// loadonce:true, //compulsory for search
//cellEdit: true, //inline edits
//cellsubmit: 'clientArray', //inline edit
caption: 'Todo List',
sortname: 'id',
sortorder: 'desc',
multiselect: true,
multiboxonly: true,
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
autowidth: true,
}).navGrid('#pager', { edit: true, add: true, del: true, search: true, refresh: true }, //search: true
{
// edit options
zIndex: 100,
url: '/TodoList/Edit',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
// add options
zIndex: 100,
url: "/TodoList/Create",
closeOnEscape: true,
closeAfterAdd: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
//delete options
zIndex: 100,
url: "/TodoList/Delete" + ,
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using TodoListApplication.DBContext;
using TodoListApplication.Models;
namespace TodoListApplication.Controllers
{
public class TodoListController : Controller
{
//
// GET: /TodoList/
public ActionResult Index()
{
return View();
}
TodoContext db = new TodoContext();
public JsonResult GetTodoLists(string sidx, string sord, int page, int rows) //Gets the todo Lists.
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var todoListsResults = db.TodoLists.Select(
a => new
{
a.Id,
a.Severity,
a.TargetDate,
a.TaskDescription,
a.TaskName,
a.TaskStatus
});
int totalRecords = todoListsResults.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
todoListsResults = todoListsResults.OrderByDescending(s => s.TaskName);
todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
todoListsResults = todoListsResults.OrderBy(s => s.TaskName);
todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = todoListsResults
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
// TODO:insert a new row to the grid logic here
[HttpPost]
public string Create([Bind(Exclude = "Id")] TodoList objTodo)
{
string msg;
try
{
if (ModelState.IsValid)
{
db.TodoLists.Add(objTodo);
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successful";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
public string Edit(TodoList objTodo)
{
string msg;
try
{
if (ModelState.IsValid)
{
db.Entry(objTodo).State = EntityState.Modified;
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
public string Delete(int Id)
{
TodoList todolist = db.TodoLists.Find(Id);
db.TodoLists.Remove(todolist);
db.SaveChanges();
return "Deleted successfully";
}
}
}
jqGrid send comma-separated list of ids in case of deleting rows in multiselect: true mode. Thus you should change string Delete(int Id) to void Delete(string id). The corresponding code could be about the following:
public void Delete(string id)
{
var ids = id.Split(',');
foreach (var id in ids) {
TodoList todolist = db.TodoLists.Find(int.Parse(id));
db.TodoLists.Remove(todolist);
}
db.SaveChanges();
}
I'd recommend you to consider too use loadonce: true option and to simplify your co return all items at once. It's the best scenario in case of displaying small number of rows (less as 1000 for example). It will simplify your server code and to improve the performance (responsibility) of the grid.
I'd recommend you additionally to verify that you use the latest version of free jqGrid (which you can download from NuGet or to load directly from CDN). You should review jqGrid options, which you use and to remove unneeded or wrong options/parameters.
I have solved my problem, with the help by #Oleg codes.
1st:
I found out that the id name that my controller uses to pass the id is "id", while my delete method in my controller says "Id" :
public string Delete(int Id) // < see this
{
TodoList todolist = db.TodoLists.Find(Id);
db.TodoLists.Remove(todolist);
db.SaveChanges();
return "Deleted successfully";
}
click here to see the debug result, pay attention to Form Data Section
So there is a name mismatched between the id specified by controller and the id that i specified in my delete method
2nd:
So i modified my delete method in controller to become:
public ActionResult Delete(string id)
{
var ids = id.Split(',');
foreach (var idsss in ids)
{
TodoList todolist = db.TodoLists.Find(int.Parse(idsss));
db.TodoLists.Remove(todolist);
}
db.SaveChanges();
var result = new { msg = "Deletion Successful ! " };
return Json(result, JsonRequestBehavior.AllowGet);
}
Now it works now, thanks to #Oleg !
Using ASP.NET MVC action method to return Json to a view in order to display the data in a EXT JS form. I am always getting the "record" value as null in the function everythingLoaded even though i can see the action method is returning the JSON data after the Ext.Create. What i am trying to achieve is populate the firstName and lastName param's passed back from the action method to the textbox inside the panel. Can you help? Below is the code
->App.JS
Ext.onReady(function() {
//Define Store
Ext.define('StudentModel', {
extend: 'Ext.data.Model',
idProperty: 'Id',
fields: [
{ name: 'Id', type: 'int' },
{ name: 'firstName', type: 'string' },
{ name: 'lastName', type: 'string' },
{ name: 'birthDate', type: 'date' },
{ name: 'street', type: 'string' },
{ name: 'apartment', type: 'string' },
{ name: 'city', type: 'string' },
{ name: 'state', type: 'string' },
],
validations: [{
type: 'presence',
field: 'firstName'
}]
});
var store = Ext.create('Ext.data.Store', {
model: 'StudentModel',
storeId: 'StudentStoreId',
proxy: {
type: 'ajax',
url: '/Home/GetStudentSubmissions',
reader: {
type: 'json',
rootProperty: 'data'
}
},
autoLoad: { callback: everythingLoaded }
}
);
function everythingLoaded()
{
var record = store.getAt(0);
//Here record is always null
Ext.form('MyPanel').getForm().loadRecord(record);
}
Ext.define('StudentView', {
extend: 'Ext.form.Panel',
id: 'MyPanel',
alias: 'widget.StudentView',
title: 'Student Information',
resizable: false,
collapsible: true,
store:store,
bodyPadding: '5',
buttonAlign: 'center',
border: false,
trackResetOnLoad: true,
layout: {
type: 'vbox'
},
defaults: {
xtype: 'textfield',
msgTarget: 'side',
labelAlign: 'top',
labelStyle: 'font-weight:bold'
},
items: [{
xtype: 'fieldcontainer',
layout: 'hbox',
defaultType: 'textfield',
width: '100%',
fieldDefaults: {
labelAlign: 'top',
labelStyle: 'font-weight:bold'
},
items: [{
fieldLabel: 'First Name',
name: 'firstName',
allowBlank: false
}, {
fieldLabel: 'Last Name',
name: 'lastName',
allowBlank: false
}]
}]
});
//Here count is always 0
var i = store.getCount();
Ext.create('widget.StudentView', {
renderTo: 'studentMasterForm'
});
});
-> C# Action Method
public JsonResult GetStudentSubmissions()
{
return Json(GetStudents(), JsonRequestBehavior.AllowGet);
}
public Student GetStudents()
{
Student studobj = new Student();
studobj.Id = 1;
studobj.firstName = "Aravind";
studobj.lastName = "R";
studobj.state = "NJ";
studobj.street = "Center Grove";
studobj.birthDate = new DateTime(1989, 6, 6);
studobj.apartment = "DD8";
studobj.city = "XYZ";
return studobj;
}
}
->Student Model Class
public class Student
{
public int Id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public DateTime birthDate { get; set; }
public string street { get; set; }
public string apartment { get; set; }
public string city { get; set; }
public string state { get; set; }
}
Your c# code returns one object "Student", but it is supposed to return an object which have an array of students as its "data" property.
You need to return an object of this type:
public class ExtStore
{
public List<Student> data = new List<Student>();
}
this way for example:
public ExtStore GetStudents()
{
Student studobj = new Student();
studobj.Id = 1;
studobj.firstName = "Aravind";
studobj.lastName = "R";
studobj.state = "NJ";
studobj.street = "Center Grove";
studobj.birthDate = new DateTime(1989, 6, 6);
studobj.apartment = "DD8";
studobj.city = "XYZ";
ExtStore exs = new ExtStore();
exs.data.Add(studobj);
return exs;
}
I have a problem with inserting data into highchart I try to customize example from http://www.highcharts.com/stock/demo
But my chart doesn't show any information, I looked at the example data, and it is in the same format as my data:
Here is my code in c#:
[HttpPost]
public JsonResult GetData()
{
...
var view= new JavaScriptSerializer().Serialize(dictionary.dicValues.Select(x => new object[] {x.Key, x.Value}));
view= Regex.Replace(view, #"\""\\/Date\((-?\d+)\)\\/\""", "$1");
view= view.Replace(#"[", "").Replace(#"]", "");
return new JsonResult
{
Data = new
{
view
},
ContentType = null,
ContentEncoding = null,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
Here is my js code for creating highchart:
$(elem).highcharts('StockChart', {
rangeSelector: {
selected: 1
},
title: {
text: "title"
},
xAxis: {
type: 'datetime',
},
yAxis: {
type: 'double',
},
series: [{
name: 'AAPL',
data: data.view,
tooltip: {
valueDecimals: 2
}
}]
});
And here is my data which I pass to the view:
"1421751600000,4.9928500000000007,1421755200000,13.314966666666665,1421758800000,8.316766666666668,1421845200000,14.738,1421848800000,7.9762000000000013"
or if I didn't erase the parentheses:
"[[1421751600000,4.9928500000000007],[1421755200000,13.314966666666665],[1421758800000,8.316766666666668],[1421845200000,14.738],[1421848800000,7.9762000000000013]]"
If someone could help me, I will be very grateful!
You should be able to simply this to:
public JsonResult GetData()
{
return new JsonResult()
{
Data = dictionary.dicValues.Select(x => new object[] {x.Key, x.Value})
};
}
The defaults for JsonResult should give you the correct settings for ContentType and it should automatically use the default serializer to serialize your object to a correct JSON string (unless you need some custom serialization).