Access to a model attribute in Javascript with Spring MVC - javascript

I have some problem accessing to model attribute in Javascript; in particular I have this controller:
#RequestMapping(value = "/dashboard")
public ModelAndView home(HttpServletRequest request, HttpServletResponse
res, Model model) {
// Return answer's dictionary from DB to dashboard view
CompQuest dizRisp = new CompQuest();
dizRisp.setDizComp(dashDao.getRispEnd());
model.addAttribute("dizRisp", dizRisp);
return new ModelAndView("dashboard");
}
and I have this Javascript file (here: only the part with the code for my chart where I want to refer to model attribute) where I want to access to model attribute "dizRisp" from my controller:
var ctx1 = document.getElementById('myChart1').getContext('2d');
var myRadarChart = new Chart(ctx1, {
type: 'radar',
data: {
labels: ['Valori e identità del SCN', 'La cittadinanza attiva',
'Il giovane volontario nel sistema del SC', 'Lavorare',
'Prevenzione e protezione', 'Normativa sicurezza',
'Rischi sulla salute in tema di ambiente'
],
datasets: [{
label: "Civiche",
data: [4, 5, 5, 2, 4, 5, 4],
fill: true,
borderJoinStyle: "round"
}],
},
options: {
maintainAspectRatio: false,
scale: {
ticks: {
stepSize: 1,
step: 1,
beginAtZero: true,
max: 5
}
}
}
});
My classes are (here: no getters and setters):
public class CompQuest {
private HashMap <String, CompRisp> dizComp;}
public class CompRisp {
private ArrayList <Risposte> rispList = new ArrayList <Risposte> ();}
public class Risposte {
int id;
Domande domande;
int valore;
int momento; }
public class Domande {
int id;
String testo;
String descrizione;
Questionario questionario; }
My .jsp file:
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js" ></script>
<script src="resources/dashboard.js" type="text/javascript"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/dashboard.css">
<title>Dashboard</title>
<style>
#import url('https://fonts.googleapis.com/css?family=Bitter|Roboto+Condensed');
#import url('https://fonts.googleapis.com/css?family=Roboto');
</style>
In particular I would want to access to my model attribute (Hashmap) in order to put in label and datasets field of my Javascript chart values from my Hashmap that contains data from my Database.
Thanks in advance to everyone that can help me!

Spring controller
#RequestMapping(value = "/dashboard")
public ModelAndView home(HttpServletRequest request,
HttpServletResponse
res, Model model) {
// Return answer's dictionary from DB to dashboard view
CompQuest dizRisp = new CompQuest();
dizRisp.setDizComp(dashDao.getRispEnd());
Gson gson = new Gson() ;
// Use Gson dependency to convert hashmap to String
String strmap = gson.toJson(dizRisp)
model.addAttribute("dizRisp", strmap);
return new ModelAndView("dashboard");
}
Javascript
<script>
$(document).ready(function(){
var element = JSON.parse('${dizRisp}');
$.each( element , function( key, value ) {
console.log(key);
console.log(value);
});
});
</script>
Hope this is what your trying to achieve.

Related

Filtering datatable with dropdown select

I am trying to filter datatable by select.
I can see the data in select but don't know how to filter it.
Here's my code.
Thanks
function getSearchList() {
$.post('#(Url.Action("GetSearchList", "ESR"))')
.success(function (data) {
if (data.length > 0) {
$.each(data, function () {
$('#Search_Id').append($('<option>', {
value: this.ID,
text: this.S_ID
}));
});
}
$(window).unblock();
})
}
and
$(document).ready(function () {
$('#Search_Id').select2({
placeholder: "Search",
allowClear: true,
});
});
and
<div class="col-sm-2">
<select class="select" id="Search_Id"></select>
</div>
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
public List<SearchId> GetSearchIdData()
{
string strSQL = string.Format(#"SELECT ID, S_ID FROM TBR");
using (var conn = SqlUtility.GetDBConnection())
{
conn.Open();
return conn.Query<SearchId>(strSQL).ToList();
}
}
and
public ActionResult GetSearchIdList()
{
JsonResult result;
List<SearchId> List = service.GetSearchIdList();
result = Json(List);
result.MaxJsonLength = int.MaxValue;
return result;
}
and
public class SearchId
{
public int ID { get; set; }
public string S_ID{ get; set; }
}
and
public List<SearchId> GetSearchIdList()
{
return repo.GetSearchIdData();
}

dataModel URL javascript function does not populate grid

Why won't the grid populate?
I have JSON string generated dynamically using java. (main . java)
[gif image of json string generation][1]
package com.queryData.main;
import com.queryData.dao.DataDAO;
import com.queryData.services.JsonServices;
import java.sql.ResultSet;
import java.util.List;
import org.json.JSONObject;
public class Main {
ResultSet resultSet = null;
DataDAO datadao = new DataDAO();
public List<JSONObject> getJsonObject() {
resultSet = datadao.getResultSet();
List<JSONObject> resList = JsonServices.getFormattedResult(resultSet);
return resList;
}
public static void main(String[] args) {
Main m = new Main();
List<JSONObject> jObj = m.getJsonObject();
for (int i = 0; i < jObj.size(); i++) {
System.out.println(jObj.get(i));
}
}
}
I have paramQuery grid loading but have a problem with the dataModel to load the data. (index . xhtml)
[gif image of grid loading with no data][2]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<!--jQuery dependencies-->
<link rel="stylesheet"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css" />
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<!--ParamQuery Grid files-->
<h:outputStylesheet name="css/pqgrid.min.css" />
<h:outputScript name="js/pqgrid.min.js" />
<!--Include Touch Punch file to provide support for touch devices-->
<h:outputScript name="js/jquery.ui.touch-punch.js" />
<script>
$(function(){
var obj = {};
obj.width = 700;
obj.height = 400;
obj.colModel = [
{ title: "Person ID", width:100, dataIndx: "person_id"},
{ title: "Full Name", width:200, dataIndx: "fullname"},
{ title: "First Name", width:150, dataIndx: "firstname"},
{ title: "Last Name", width:150, dataIndx: "lastname"}
];
<!-- reference to load remote data -->
var dataModel = {
recIndx: "personid",
location: "remote",
sorting: "local",
paging: "local",
dataType: "JSON",
method: "GET",
sortIndx: "lastname",
sortDir: "up",
url: "main.java"
, getData: function (dataJSON) {
var data = dataJSON.data;
return { data: dataJSON.data };
}
}
<!-- KEY PART TO LOAD DATA -->
$("div#grid_array").pqGrid( obj );
});
</script>
</h:head>
<h:body>
<div id="grid_array"></div>
</h:body>
</html>
I have altered the URL but do not know how the URL reference should be written, below is the script I am currently trying to correct
<h:head>
<!--jQuery dependencies-->
<link rel="stylesheet"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css" />
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<!--ParamQuery Grid files-->
<h:outputStylesheet name="css/pqgrid.min.css" />
<h:outputScript name="js/pqgrid.min.js" />
<!--Include Touch Punch file to provide support for touch devices-->
<h:outputScript name="js/jquery.ui.touch-punch.js" />
<script>
$(function()
{
<!-- reference to load remote data -->
var dataModel =
{
location: "remote",
sorting: "local",
dataType: "JSON",
method: "GET",
url: "json",
getData: function (dataJSON) {return { data: dataJSON.data };}
}
<!-- reference to create column titles -->
var obj = {dataModel:dataModel};
obj.colModel =
[
{ title: "Person ID", width:100, dataIndx: "person_id"},
{ title: "Full Name", width:200, dataIndx: "fullname"},
{ title: "First Name", width:150, dataIndx: "firstname"},
{ title: "Last Name", width:150, dataIndx: "lastname"}
];
<!-- reference to initiate the request -->
$("div#grid_array").pqGrid( obj );
}
);
</script>
</h:head>
<h:body>
<div id="grid_array"></div>
</h:body>
These are the two servlets that generate the JSON string, I need to modify from being a LIST to a string to generate JSON data in this format.
{"data": [ row1, row2, ..] }
and retrievable through a URL via GET HTTP request in my VIEW index . xhtml
The two beans and the one index VIEW:
first bean -
package com.queryData.services;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
public class JsonServices {
public static List<JSONObject> getFormattedResult(ResultSet rs) {
// List<JSONObject> resList = new ArrayList<JSONObject>();
List<JSONObject> resList = "{\"data\":" + new ArrayList<JSONObject>() + "}";
// above is the attempt to modify
try {
// get column names
ResultSetMetaData rsMeta = rs.getMetaData();
int columnCnt = rsMeta.getColumnCount();
List<String> columnNames = new ArrayList<String>();
// loop to get all column names
for (int i = 1; i <= columnCnt; i++) {
// adding all retrieved column names to List object
columnNames.add(rsMeta.getColumnName(i).toUpperCase());
}
while (rs.next()) {
// convert each object to an human readable JSON object
JSONObject obj = new JSONObject();
for (int i = 1; i <= columnCnt; i++) {
String key = columnNames.get(i - 1);
String value = rs.getString(i);
obj.put(key, value);
}
resList.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return resList;
}
}
second bean -
package com.queryData.main;
import com.queryData.dao.DataDAO;
import com.queryData.services.JsonServices;
import java.sql.ResultSet;
import java.util.List;
import org.json.JSONObject;
public class Main {
ResultSet resultSet = null;
DataDAO datadao = new DataDAO();
public List<JSONObject> getJsonObject() {
resultSet = datadao.getResultSet();
List<JSONObject> resList = JsonServices.getFormattedResult(resultSet);
return resList;
}
public static void main(String[] args) {
Main m = new Main();
List<JSONObject> jObj = m.getJsonObject();
for (int i = 0; i < jObj.size(); i++) {
System.out.println(jObj.get(i));
}
}
}
VIEW index . xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"/>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"/>
<h:outputStylesheet name="css/pqgrid.min.css"/>
<h:outputScript name="js/pqgrid.min.js"/>
<h:outputScript name="js/jquery.ui.touch-punch.js"/>
<script>
$(function(){
var obj = {};
obj.width = 700;
obj.height = 400;
obj.colModel = [
{ title: "Person ID", width:100, dataIndx: "person_id"},
{ title: "Full Name", width:200, dataIndx: "fullname"},
{ title: "First Name", width:150, dataIndx: "firstname"},
{ title: "Last Name", width:150, dataIndx: "lastname"}
];
var dataModel = {
recIndx: "personid",
location: "remote",
sorting: "local",
paging: "local",
dataType: "JSON",
method: "GET",
sortIndx: "lastname",
sortDir: "up",
url: "main"
, getData: function (dataJSON) {
var data = dataJSON.data;
return { data: dataJSON.data };
}
}
$("div#grid_array").pqGrid( obj );
});
</script>
</h:head>
<h:body>
<div id="grid_array"></div>
</h:body>
</html>
The deployed test app can be viewed at deployed test run
You can do as follow:
Create a backing bean
Persons.java
#ManagedBean(name="persons")
#SessionScoped
public class Persons {
ResultSet resultSet = null;
DataDAO datadao = new DataDAO();
public List<JSONObject> people = JsonServices.getFormattedResult(datadao.getResultSet());
/** getter and setter **/
}
In your xhtml, you add a hidden element where you put data from backing bean
<h:inputHidden id="hiddenPeople" value="#{persons.people}" />
In your xhtml, javascript section
<script>
$(function() {
var peopleList = $('#hiddenPeople');
var peopleJson = JSON.parse(peopleList)
// display peopleJson
});
</script>
Now, I am not sure if the List people will be converted to a string, so you may want to convert that to a String rather than a List.

ASP.NET MVC serialize data to morris area chart

I trying to use morris area chart, I don't know how correctly to serialize data and send date which morris area chart can understand.
This is method in HomeController which get data from DB.
public ActionResult GetData()
{
List<GraphData> GraphDataList = new List<GraphData>();
var user = db.Users.Where(p => p.Email == User.Identity.Name).Single();
var Requests = db.Transactions.Where(p => p.Package_id != null && p.User_id == user.Id);
DateTime day = new DateTime();
int CountPerDay = 0;
// count of request per day
foreach (var request in Requests)
{
if (day.Year == request.Date.Year && day.Day == request.Date.Day)
{
CountPerDay++;
}
else
{
// To 2016-12-03 format of date
string Date = day.Year + "-" + day.Month + "-" + day.Day;
GraphDataList.Add(new GraphData(Date, CountPerDay));
CountPerDay = 0;
day = request.Date;
}
}
// First elem in list is wrong
GraphDataList.RemoveAt(0);
return Json(GraphDataList, JsonRequestBehavior.AllowGet);
}
GraphData class
public class GraphData
{
public string label { get; set; }
public int value { get; set; }
public GraphData(string label, int value)
{
this.label = label;
this.value = value;
}
public GraphData()
{
}
}
Area chart in html code
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Request statistic
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div id="area-example"></div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
And func which get data from controller and send to Morris.Area
<!--Get Data for Graph-->
<script type="text/javascript">
$(document).ready(function() {
$.get('#Url.Action("GetData","Home")', function (result) {
new Morris.Area({
// ID of the element in which to draw the chart.
element: 'area-example',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [result],
// The name of the data record attribute that contains x-values.
xkey: 'label',
ykeys: ['value'],
labels: ['Success requests'],
pointSize: 2,
hideHover: 'auto',
resize: true
});
});
});
</script>
So the result is the clear panel without graph
But if a init data like this
<!--Get Data for Graph-->
<script type="text/javascript">
$(document).ready(function() {
$.get('#Url.Action("GetData","Home")', function (result) {
new Morris.Area({
// ID of the element in which to draw the chart.
element: 'area-example',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [
{ label: '2016-12-3', value: 150},
{ label: '2016-12-4', value: 221},
{ label: '2016-12-5', value: 43},
{ label: '2016-12-6', value: 21},
{ label: '2016-12-7', value: 312}
],
// The name of the data record attribute that contains x-values.
xkey: 'label',
ykeys: ['value'],
labels: ['Success requests'],
pointSize: 2,
hideHover: 'auto',
resize: true
});
});
});
</script>
the result is
Solution is to use this, because you have already returned a json array using ajax call. So, you do not need data:[result],all you need is data:result.
new Morris.Area({
// ID of the element in which to draw the chart.
element: 'area-example',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: result,
// The name of the data record attribute that contains x-values.
xkey: 'label',
ykeys: ['value'],
labels: ['Success requests'],
pointSize: 2,
hideHover: 'auto',
resize: true
});

How to pass Dictionary from c#(server) to javascript(client)

I have a function in c# that builds dictionary ,I need to pass this dictionary to my java-script function.
This is what I have tried
My server function
public partial class login : System.Web.UI.Page
{
protected Dictionary<string, string> GetTradingTypeToSelect()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
try {
string Types =GetString("some text);
var items = Types.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split(new[] { '=' }));
foreach (var item in items)
{
dict.Add(item[1], item[0]);
}
//this working 100%
}
catch (Exception ex)
{
}
return dict;
}
}
My client:
$(document).ready(function () {
$("#Account").keyup(function () {
var TradingTypeToSelect = '<%=GetTradingTypeToSelect();%>';
//TradingTypeToSelect is equals to string '<%=GetTradingTypeToSelect();%>'
var test = TradingTypeToSelect[0].key;
var test2 = TradingTypeToSelect[0].value;
});
});
What am I missing here?
You can create a [WebMethod] in the code behind and call it from javascript using $.ajax.Below is a complete example:
Code behind:
[System.Web.Services.WebMethod]
public static Dictionary<string, string> GetTradingTypeToSelect()
{
var dict = new Dictionary<string, string>();
dict.Add("1", "Item 1");
dict.Add("2", "Item 2");
return dict;
}
.ASPX:
<head runat="server">
<title></title>
<script src="//code.jquery.com/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(function () {
$("#Account").keyup(function () {
$.ajax({
type: "POST",
url: "AjaxCallExample.aspx/GetTradingTypeToSelect",
contentType: "application/json;charset=utf-8",
success: function (data) {
alert(data.d["1"]);
alert(data.d["2"]);
},
error: function (errordata) {
console.log(errordata);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="Account" type="text" />
</form>
</body>
How about exposing the dictionary in the view model:
public Dictionary<string, string> TradingTypesToSelect { get; set; }
And iterate over the dictionary inside the <script> block, creating a JavaScript associative array, like so:
<script>
var tradingTypesToSelect = {};
<% foreach (var tradingType in Model.TradingTypesToSelect) { %>
tradingTypesToSelect["<%= tradingType.Key %>"] = "<%= tradingType.Value %>";
<% } %>
</script>
At least this way you don't have to make another call (via AJAX) to retrieve additional data.
I believe you need to make a WebMethod to enable the server function to be called from the client side. Here is an example:
Calling ASP.Net WebMethod using jQuery AJAX

Telerik MVC, Combobox changing the CSS of an item

My ASP.NET MVC-3 application is using the previous version of Telerik MVC Extensions combobox. I am trying to change the style of an item in the list.
Here is the model:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public bool DisplayBold { get; set; }
public string Value
{
get
{
return string.Format("{0}|{1}", this.Id, this.DisplayBold.ToString());
}
}
}
The Controller:
var people = new List<Person>();
people.Add(new Person { Id = 1, Name = "John Doe", DisplayBold = true });
people.Add(new Person { Id = 2, Name = "Jayne Doe", DisplayBold = false });
ViewData["people"] = people;
return View();
The Combobox:
<% Html.Telerik().ComboBox()
.Name("ComboBox")
.BindTo(new SelectList((IEnumerable<Person>)ViewData["people"], "Id", "Name"))
.ClientEvents(events => events
.OnChange("ComboBox_onChange")
.OnLoad("ComboBox_onLoad")
.OnOpen("ComboBox_OnOpen"))
.Render();
%>
I tried the following and it did change the first item:
var item = combobox.dropDown.$items.first();
item.addClass('test');
However when I tried to change the CSS when it is Ture:
var combobox = $(this).data('tComboBox');
$.each(combobox.dropDown.$items, function (idx, item) {
if (combobox.data[idx].Value.split('|')[1] == 'True') {
alert(item);
$(item).addClass('test');
}
});
It did not work!
This is the version after user373721 marked this as answered
While i was rewriting my previous answer and browsing the forums user373721 marked my old revision as answered.
I am sorry i searched the forum of telerik to see how you could hook into the databinding to influence the css. I could not find a good match to your problem.
One muddy workaround (getting desperated here) could be to add html to the names that should be displayed bold:
public class Person
{
public string NameText { get; }
{
get
{
if(this.DisplayBold) {
return "<b>" + this.Name + "</b>";
} else
return this.Name;
}
}
}
So instead of binding to Name you would bind to NameText.
You may need to take care of html-conversion.
In my last search i found a post that may help. And now i found a post that could be from you
By the way in the forums i have read that there were several bug
fixes that could be important for your goal.
Which telerik mvc-release are you using?
Solution to set style with the new mvc-telerik extensions (kendo)
Hi based on the example at telerik mvc comboBox usage i used a template approach. At jsfiddle you can find a working example for the new telerik mvc extension (kendo).
Use of template to set style based on the underlying datasource:
<script id="template" type="text/x-kendo-tmpl">
# if (data.displayBold) { #
<span style="font-weight: bolder;">${ data.name }</span>
# } else { #
<span style="font-weight: normal;">${ data.name }</span>
# } #
</script>
On document.ready bind the combobox:
// use of templates
$("#titles").kendoComboBox({
dataTextField: "name",
dataValueField: "Id",
// define custom template
template: kendo.template($("#template").html()),
dataSource: musicians
});
The dataSource is an array of objects similar to your person class:
var musicians= [{ id: 1, name: "Melody Gardot", displayBold: true }
, { id: 2, name: "Lynn Withers", displayBold: false }
, { id: 3, name: "Blue Ray", displayBold: true }
, { id: 4, name: "Club de Belugas", displayBold: true }
, { id: 5, name: "Mizzy Li", displayBold: false }
];
hth

Categories

Resources