building a chart from a backing bean using google chart tools - javascript

I'm trying to draw a chart using google chart tools. I'd like to know if there is a way to take the array values from my backing bean using Javascript. I have the following code but, when I test it, it looks like it doesn't get the backing bean:
my xhtml:
<?xml version="1.0" encoding="UTF-8" ?>
<!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:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:fn="http://java.sun.com/jsp/jstl/functions">
<ui:composition template="/pages/menu.xhtml">
<ui:define name="conteudo">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current'); // Don't need to specify chart libraries!
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
dataTable: ["#{chartBean.countries}", "#{chartBean.numbers}"],
options: {'title': 'Countries'},
containerId: 'vis_div'
});
wrapper.draw();
}
</script>
<div id="vis_div" style="width: 600px; height: 400px;"></div>
</ui:define>
</ui:composition>
</html>
my backing bean:
#ManagedBean
#RequestScoped
public class ChartBeean {
private String[] countries = {"","Germany","USA","Brazil","Canada","France","Russia"};
private int[] numbers = {0,700,300,400,500,600,800};
public String[] getCountries() {
return countries;
}
public void setCountries(String[] countries) {
this.countries = countries;
}
public int[] getNumbers() {
return numbers;
}
public void setNumbers(int[] numbers) {
this.numbers = numbers;
}
}
Can anyone help me with this?
PS:I know there is a specific api to use google charts in primefaces, but I would like to use the pure google chart api.

for your query regarding "..it looks like it doesn't get the backing bean"
Your are using #{chartBean.countries} and your Managed Bean name is ChartBeean.
You need to use #{chartBeean.countries} and "#{chartBeean.numbers}"
Working Code for Charts -
You do not need the " " on
dataTable : [ #{chartBeean.countriesString}, #{chartBeean.numbersString} ])
I have added ' in the String for countries.
XHTML
<h:head>
<title>Charts Test</title>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current'); // Don't need to specify chart libraries!
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var wrapper = new google.visualization.ChartWrapper(
{
chartType : 'ColumnChart',
dataTable : [ #{chartBeean.countriesString},
#{chartBeean.numbersString} ],
options : {
'title' : 'Countries'
},
containerId : 'chart_div'
});
wrapper.draw();
}
</script>
</h:head>
<h:body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</h:body>
</html>
ManagedBean
package com;
import java.util.Arrays;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean
#RequestScoped
public class ChartBeean {
private String[] countries = { "'Germany'", "'USA'", "'Brazil'", "'Canada'", "'France'", "'Russia'" };
private String[] numbers = { "700", "300", "400", "500", "600", "800" };
public ChartBeean() {
super();
System.out.println("ChartBeean..");
}
#PostConstruct
public void init() {
System.out.println("ChartBeean init..");
}
public String getCountriesString() {
// ['Germany', 'USA', 'Brazil', 'Canada', 'France', 'Russia']
String deepToString = Arrays.deepToString(countries);
System.out.println(deepToString);
return deepToString;
}
public String getNumbersString() {
// [700, 300, 400, 500, 600, 800]
String deepToString = Arrays.deepToString(numbers);
System.out.println(deepToString);
return deepToString;
}
}

Related

Access to a model attribute in Javascript with Spring MVC

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.

laravel vue.js select list from database

I just begun Vue.js and I have some issues with it:
I’m currently working with Laravel, a PHP framework.
I would like to do a select list for a research, i have different applications but there are all related to different countries. And when I select a country I would like that only apps with this country appear.
I used to use php but we have to reload the page each time and it’s not very quick and easy to use.
My main page is like that:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>VueJS</title>
<link rel="stylesheet" href="">
<script src="/js/vue.js"></script>
</head>
<body>
<div id="app">
<div id="country">
<select v-model="selectedcountry">
<option v-for="option in options" v-bind:value="option.value">#{{ option.text }}
</option>
</select>
<span>Sélectionné : #{{ selectedcountry }}</span>
</div>
<script src="/js/app.js"></script>
</body>
</html>'
And my app.js :
new Vue({
el: '#country',
data: {
selectedcountry: 'All Countries',
options: [
{ text: 'All Countries', value: 'world' },
{ text: 'Denmark', value: 'denmark' },
{ text: 'France', value: 'france' },
]
}
})'
And in my database my table is : "cards" with an attribute call "country".
My controller is :
<?php
namespace App\Http\Controllers;
use App\Apps;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function search(Request $request)
{
if ($request->has('Country')) {
$apps = Apps::where('Country', $request->Country)->get();
return view('index', compact('apps'));
}
}
}
How can I do that?
My controller is :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Apps;
class SearchController extends Controller
{
public function search(Request $request){
if( $request->has('Country') ){
$apps = Apps::where('Country',$request->Country)->get();
return view('index',compact('apps'));
}
}
}
You must create vue component for your application. Working with component makes your code easier and well structured, also you are confusing yourself with #country and #app and you also need to define your form elements for vue.

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.

How to render events in FullCalendar from JSON in ASP.NET MVC?

I've been able to get FullCalendar to load in my webpage but I can't seem to successfully pass my test JSON data to the calendar and have it render events. I'm not sure what I'm doing wrong.
I'm following this website's example and I even downloaded their source code and was able to run it successfully in my dev environment. My code seems to almost completely mirror their's yet I still can't render events. I even went back and added javascript files to my bundles just in case that was the issue but to no success.
Any ideas?
Bundles:
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css",
"~/Content/themes/base/jquery.ui.all.css",
"~/Content/fullcalendar.css"));
/*Kendo UI Instructions that were followed
* http://docs.telerik.com/kendo-ui/aspnet-mvc/asp-net-mvc-5
*/
bundles.Add(new ScriptBundle("~/bundles/kendo").Include(
"~/Scripts/kendo/2016.2.714/kendo.webcomponents.min.js",
// "~/Scripts/kendo/kendo.timezones.min.js", // uncomment if using the Scheduler
"~/Scripts/kendo/2016.2.714/kendo.aspnetmvc.min.js",
"~/Scripts/kendo/2016.2.714/jquery.min.js",
"~/Scripts/kendo/2016.2.714/kendo.ui.core.min.js",
"~/Scripts/kendo/2016.2.714/kendo.calendar.min.js",
"~/Scripts/kendo/2016.2.714/kendo.popup.min.js",
"~/Scripts/kendo/2016.2.714/kendo.datepicker.min.js"));
bundles.Add(new StyleBundle("~/Content/kendo/css").Include(
"~/Content/kendo/2016.2.714/kendo.common-bootstrap.min.css",
"~/Content/kendo/2016.2.714/kendo.bootstrap.min.css",
"~/Content/kendo/2016.2.714/kendo.common.min.css",
"~/Content/kendo/2016.2.714/kendo.defualt.min.css"));
bundles.Add(new ScriptBundle("~/bundles/fullcalendar").Include(
"~/Scripts/jquery-ui-1.12.0.min.js",
"~/Scripts/moment.min.js",
"~/Scripts/fullcalendar.min.js"));
bundles.IgnoreList.Clear();
}
_Layout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Time Zone Event Calendar</title>
#Styles.Render("~/Content/kendo/css")
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/kendo")
#Scripts.Render("~/bundles/fullcalendar")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Time Zone Event Calendar", "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - Time Zone Event Calendar</p>
</footer>
</div>
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
Index:
#{
ViewBag.Title = "Home Page";
}
<head>
#section scripts{
<script type="text/javascript">
$(document).ready(function ()
{
$('#calendar').fullCalendar(
{
header:
{
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: false,
events: "/home/loadevents/"
})
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#pickDateTime").kendoDateTimePicker({
culture: "es-Es",
interval: 1,
format: "yyyy/MM/dd hh:mm tt",
parseFormats: ["MMMM yyyy", "HH:mm"]
});
});
</script>
}
</head>
<body>
<div id="headerBar">
<div id="datepicker">
<form method="post">
<input id="pickDateTime" name="DateTimePicker" />
<input type="submit" value="Add" />
</form>
</div>
</div>
<div id="calendar"></div>
</body>
HomeController:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult LoadEvents (double start, double end)
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var eventList = GetEvents();
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
private List<CalendarEventsViewModel> GetEvents()
{
List<CalendarEventsViewModel> eventList = new List<CalendarEventsViewModel>();
CalendarEventsViewModel newEvent = new CalendarEventsViewModel
{
ID = "1",
EventName = "Event 1",
StartDateString = DateTime.Now.AddDays(1).ToString("s"),
EndDateString = DateTime.Now.AddDays(1).ToString("s"),
AllDay = false
};
eventList.Add(newEvent);
newEvent = new CalendarEventsViewModel
{
ID = "1",
EventName = "Event 3",
StartDateString = DateTime.Now.AddDays(2).ToString("s"),
EndDateString = DateTime.Now.AddDays(3).ToString("s"),
AllDay = false
};
eventList.Add(newEvent);
return eventList;
}
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
}
CalendarEventsViewModel:
public class CalendarEventsViewModel
{
public string ID { get; set; }
public string EventName { get; set; }
public string EventText { get; set; }
public string StartDateString { get; set; }
public string EndDateString { get; set; }
public bool AllDay { get; set; }
}
I think you have made the same mistake I did when I first set it up, the example you are looking at only works for version one of FullCalendar. In version two it's not a unix timestamp your LoadEvents action receives.
It's a moment object that is passed to the action, if you remove your ConvertFromUnixTimestamp method and change your start and end parameters from double to DateTime I think it will start working.
If you break point your LoadEvents action without making any changes I am pretty confident it's not even being called.
Your property names should match those of the event object otherwise it will treat them like non standard fields.

ASP.Net MVC Scripts not working with controller's default action url. Same is working with controller/action url

When mvc application is queried with controller name alone in the url without specifying action, the page is rendered but ajax/scripts are not working, whereas the same page when queried with action in the url, is working as expected.
Not working url: http://localhost:port/Search --> Page rendering is fine but scripts are not working - Search results are not showing up
Working url: http://localhost:port/Search/Index --> Page and scripts are working as expected - Search results are showing up
C#:
public class SearchController : Controller
{
private readonly List<string> _cars;
public SearchController()
{
_cars = new List<string>{"Corolla","Camry","Civic","Land Rover","Range Rover","Polo"};
}
public ActionResult Index()
{
return View();
}
public async Task<JsonResult> GetMatchingResults(string filter)
{
var results = await Task.Run(() => GetSearchResults(filter));
return new JsonResult() { Data = results,JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
private List<string> GetSearchResults(string filter)
{
var results = _cars.Where(car => car.Contains(filter));
return results.ToList();
}
}
HTML:
<html>
<head>
#using System.Web.Optimization
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/ApplicationScripts/SearchViewJS.js" type="text/javascript"></script>
<title>SearchView</title>
</head>
<body>
<div>
<input class="searchText" type="search" />
</div>
<div>
<input class="searchResults" type="text" />
</div>
</body>
</html>
JS:
$(document).ready(function () {
$(".searchText").on('input', function (event) {
var filter = $(event.currentTarget).val();
search(filter).then(display);
});
function search(filter) {
return $.getJSON('GetMatchingResults/', { 'filter': filter });
}
function display(result) {
$(".searchResults").val(result);
}
})
It is because of the context of
$.getJSON('GetMatchingResults/', { 'filter': filter });
In the first case that will be trying to hit /GetMatchingResults the second tries to hit /search/GetMatchingResults. A fix could be to use
$.getJSON('/search/GetMatchingResults/', { 'filter': filter });
Or even better would be to generate the path from a HTML helper that will route correctly if you update your routing rules. This would look something like
$.getJSON('#Url.Action("GetMatchingResults", "Search")', { 'filter': filter });

Categories

Resources