Here is my controller class:
global class MyJSController {
public static String objj { get; set; }
#RemoteAction
public static String getObject_name(){
return objj;
}
#RemoteAction
public static void setObject_name(String s){
objj=s;
}
public String accountName { get; set; }
public static Account account { get; set; }
public static List<Order__c> order{get;set;}
public static List<Units__C>unit{get;set;}
public static List<Widget__c> widget{get;set;}
public MyJSController() {
setObject_name('Order');
} // empty constructor
#RemoteAction
global static Account getAccount(String accountName) {
account = [SELECT id, name, phone, type, numberofemployees
FROM Account WHERE name = :accountName];
return account;
}
#RemoteAction
global static Order__c[] getOrder(){
return ([SELECT id,Name,Date__c,Inbound_Orders__c,Outbound_Orders__c from Order__c]);
}
#RemoteAction
global static List<Units__c> getUnits(){
unit=[SELECT id,Name,Date__c,Inbound_Units__c,Outbound_Units__c from Units__c];
return unit;
}
#RemoteAction
global static List<Widget__c> getWidget(){
widget=[SELECT id,Name,Date__c,Inbound_Widgets__c,Outbound_Widgets__c from Widget__c];
return widget;
}
}
And here is my visualforce page:
<apex:page controller="MyJSController">
<apex:form >
<apex:selectList id="chooseColor" value="{!object_name}" size="1" onchange="initCharts()" >
<apex:selectOption itemValue="Order" itemLabel="Order"/>
<apex:selectOption itemValue="Unit" itemLabel="Unit"/>
<apex:selectOption itemValue="Widget" itemLabel="Widget"/>
</apex:selectList>
</apex:form>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(initCharts);
function initCharts() {
// Following the usual Remoting syntax
// [<namespace>.]<controller>.<method>([params...,] <callbackFunction>(result, event) {...}
// namespace : abhinav
// controller : GoogleChartsController
// method : loadOpps
MyJSController.getOrder(
function(result, event){
// load Column chart
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
for(var i =0; i<result.length;i++){
var r = result[i];
data.addRow([r.Name,r.Inbound_Orders__c]);
}
var data1=new google.visualization.DataTable();
data1.addColumn('string','Topping');
data1.addColumn('number','Slices');
for(var i=0;i<result.length;i++)
{
var r=result[i];
data1.addRow([r.Name,r.Inbound_Orders__c]);
}
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
var chart1= new google.visualization.AreaChart(document.getElementById('chart_hh'));
chart.draw(data, options);
chart1.draw(data1,options); }, {escape:true});
MyJSController.getObject_name(function(event,result){
alert('Hello'+result);
document.getElementById('dddd').innerHTML=String.ValueOf(result); },{escape:true});
}
</script>
<div id="chart_div" ></div>
<div id="chart_hh"></div>
<div id="dddd">Helloojjfs</div>
</apex:page>
When I call MyJSController.getObject_name in script tag (4th last line in script tag) in result I am getting [Object Object]. But I need String Order which I initialize in the constructor. Can you please tell me where I am wrong and to rectify this mistake?
I believe the issue is that your argument names are backwards. It should be:
MyJSController.getObject_name(function(result, event)
So the alert you are getting of an object is actually the event object.
Related
I am brand new on Apache Wicket and I need to set value on a Java attribute. This value comes from a var on JS filled by a specific function from a specific GIS lib (https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html). This setting must be triggered by some component behavior.
Here is a simplified example code:
Wicket web page:
public class MapPage extends WebPage {
private static final long serialVersionUID = 1L;
private Integer coordinates;
// getters and setters
}
Wicket html:
<html xmlns:wicket="http://wicket.apache.org">
<head>
<!-- metas, scripts, and css imports -->
</head>
<body>
<script>
// component declarations
var coordinates = ''
map.on('draw:edited', function (e) {
e.layers.eachLayer(function(layer) {
coordinates = toWKT(layer);
// send coordinates to coordinates java attribute ??? how??
});
});
</script>
</body>
Thanks a lot!
This is a piece of code from one of my projects, where I want to handle a click on a (HighCharts) chart. It passes data to Wicket and Wicket then updates another panel to display details related to the click.
The relevant javascript part, where interactionurl is actually the callbackScript that is generated by the behavior later on:
interactionurl(JSON.stringify(myDataToPass));
The behaviour:
this.add( this.interactionbehavior = new AbstractDefaultAjaxBehavior()
{
#Override
protected void respond( final AjaxRequestTarget target )
{
RequestCycle cycle = RequestCycle.get();
WebRequest webRequest = (WebRequest) cycle.getRequest();
String param1 = webRequest.getQueryParameters().getParameterValue( "mydict" ).toString( "" );
//param1 contains the JSON map passed from javascript.
//you can also do stuff now, like replacing components using ajax
}
#Override
protected void updateAjaxAttributes( AjaxRequestAttributes attributes )
{
super.updateAjaxAttributes( attributes );
attributes.getExtraParameters().put( "mydict", "__PLACEHOLDER__" );
}
#Override
public CharSequence getCallbackScript()
{
String script = super.getCallbackScript().toString().replace( "\"__PLACEHOLDER__\"", "data" );
return script;
}
} );
You only need to pass the interaction url to the page on some moment. For this you can use renderHead in the component that has the behaviour:
#Override
public void renderHead( final IHeaderResponse response )
{
...
//use the `setupCallback` to store the callback script somewhere.., I store it in 'interactionurl'
String script = String.format( " setupCallback(this.interactionbehavior.getCallbackScript()); ");
response.render( OnDomReadyHeaderItem.forScript( script )
}
im having trouble with getting pushpins on my map.
Im using Bing maps and i want to show some coordinates on it. i have followed a tutorial on youtube but still don't manage to make it.
The link is here https://www.youtube.com/watch?v=uVeuib8_MWw&t=2s
So this is what i got!
In my class model i got
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Map.Models
{
public class Locations
{
public string latitude { get; set;}
public string longitude { get; set;}
public Locations(string latitude, string longitude)
{
this.latitude = latitude;
this.longitude = longitude;
}
}
}
In my controller i have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Map.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetLocations()
{
var locations = new List<Models.Locations>()
{
new Models.Locations("12.505353","55.335292"),
new Models.Locations("13.505353","55.485292"),
new Models.Locations("13.655353","55.665292")
};
return Json(locations, JsonRequestBehavior.AllowGet);
}
}
}
And at the end its the view. Here is the map aswell and the pushpins.
#{
ViewBag.Title = "Home Page";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
$(document).ready(function () {
var map = null;
function LoadMap() {
map = new Microsoft.Maps.Map(
document.getElementById('myMap'),
{
credentials: "Bing map key"
});
}
LoadMap();
$('#btnShowLocations').click(function () {
var url = "/Home/GetLocations";
$.getJSON(url, null, function (data) {
$.each(data, function (index, LocationData) {
var pushpin = new Microsoft.Maps.pushpin(map.getCenter(), null);
pushpin.setLocation(new Microsoft.Maps.Location(
LocationData.latitude,
LocationData.longitude));
map.entities.push(pushpin);
map.setView({
zoom: 4, center: new Microsoft.Maps.Location(23.505353, 78.485292)
});
});
});
});
});
</script>
<h2>Bing Map integration in ASP.NET</h2>
<input type="button" id="btnShowLocations" value ="Show All Locations" />
<div id="myMap" style="position:relative; width:600px; height:600px;">
</div>
The map is working and i get no errors. My problem is that when i press the button nothing happens. What i want is that when the button is pressed there should be 3 pushpins on the given coordinates.
Thanks so very much for reading! i hope i can get it to work!
A few issues and recommendations:
The main issue is that your latitude and longitude values are strings and are never parsed as floats/numbers. As such the map is getting string values for locations when it is expecting numbers.
Your code is using Bing Maps V7 which was replaced by V8 a while ago. V7 is nearing end of life and will be turned off at the end of June. This is the new map script URL to V8: http://www.bing.com/api/maps/mapcontrol
document.ready will fire long before the map script will load as it loads asynchronously. In fact, document.ready sometimes will fire before the whole page is loaded which means your map div might not event be available. I suggest using the callback parameter of the map script UR: for example: http://www.bing.com/api/maps/mapcontrol?callback=LoadMap
You are setting the view of the map in a loop, this should work, but will cause a lot of extra refreshes for nothing which will cost you in load performance.
A couple of recommendations:
add your pushpins to an array then add the array to the map. This will reduce the number of refreshes needed.
move your scripts to the bottom of the page and call the map script URL last since it loads asynchronously. When the map script is cached it and you press "refresh", the callback gets called instantly and often before the rest of your code is loaded. Moving this line of code to the bottom allows your page to load the fastest it can.
Here is some suggested modifications to your code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Map.Models
{
public class Locations
{
public double latitude { get; set;}
public double longitude { get; set;}
public Locations(double latitude, double longitude)
{
this.latitude = latitude;
this.longitude = longitude;
}
}
}
Your controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Map.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetLocations()
{
var locations = new List<Models.Locations>()
{
new Models.Locations(12.505353,55.335292),
new Models.Locations(13.505353,55.485292),
new Models.Locations(13.655353,55.665292)
};
return Json(locations, JsonRequestBehavior.AllowGet);
}
}
}
Your view:
#{
ViewBag.Title = "Home Page";
}
<h2>Bing Map integration in ASP.NET</h2>
<input type="button" id="btnShowLocations" value ="Show All Locations" />
<div id="myMap" style="position:relative; width:600px; height:600px;"></div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var map = null;
function LoadMap() {
map = new Microsoft.Maps.Map('#myMap', {
credentials: "Bing map key"
});
}
$('#btnShowLocations').click(function () {
var url = "/Home/GetLocations";
$.getJSON(url, null, function (data) {
var pins = [];
$.each(data, function (index, LocationData) {
var pushpin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(
LocationData.latitude,
LocationData.longitude));
pins.push(pushpin);
});
map.entities.push(pins);
map.setView({
zoom: 4, center: new Microsoft.Maps.Location(23.505353, 78.485292)
});
});
});
</script>
<script type="text/javascript" src="https://www.bing.com/api/maps/mapcontrol?callback=LoadMap" async defer></script>
I'm constructing a MVC5 Web App and want to make a dynamic page view by using Knockout.js. However, I have found that Knockout.Mapping doesn't seem to work correctly in my project.
As you see Intellisense does not the suggestion for the mapping plugin (I have included the reference of the plugin in the _reference.js). And it fails to show the second alert written when I complete this line forcibly.
Do I have to do something more to make it work correctly?
#if (false)
{
<script src = "~/Scripts/knockout-3.4.0.js" ></script >
<script src = "~/Scripts/knockout.mapping-latest.js"></script >
}
<script type="text/javascript" src="#Url.Content("~/Scripts/knockout-3.4.0.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/knockout.mapping-latest.js")"></script>
//~~body~~//
<script type="text/javascript">
alert("1");
var json = '#Html.Raw(Json.Encode(Model))';
b = ko.mapping.fromJson(json); //"mapping" is not suggested when "ko." is put.
//b = ko.mapping.fromJson(Model); //mistake at the original post
ko.applyBindings(b);
alert("2"); // not showed when the previous two lines is active.
</script>
Take a look at the help available here.
I think the example you will need to create your mapping is this:
ko.mapping.fromJS(#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)))
Try this.
var ViewModel = function() {
var self = this;
self.formData2 = ko.mapping.fromJS(#Html.Raw(Json.Encode(Model)));
}
and in your controller:
public ActionResult Index()
{
return View(new ExecutivoViewModel());
}
My ViewModel Class:
public class ExecutivoViewModel
{
public ExecutivoViewModel() { }
public ExecutivoViewModel(Executivo entidade)
{
this.ExecutivoId = entidade.ExecutivoId;
this.Nome = entidade.Nome;
this.Cargo = entidade.Cargo;
this.Inativo = entidade.Inativo;
}
[DisplayName("Executivo ID")]
[Required]
public int ExecutivoId { get; set; }
[DisplayName("Nome")]
[MaxLength(50)]
[Required]
public string Nome { get; set; }
[DisplayName("Cargo")]
[MaxLength(50)]
[Required]
public string Cargo { get; set; }
[DisplayName("Inativo")]
public bool Inativo { get; set; }
Sorry for delaying follow-up. Finally I make it working by using
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
//~~body~~//
#section scripts{
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
}
and show the suggest by putting
/// <reference path="knockout.mapping-latest.js" />
after the reference of the core library of knockout.js in _reference.js.
I'm trying to populate a data table from a List object and then display the result in a pie chart. For some reason which I cannot identify the pie chart is not showing in the browser (blank page). Below is my code. Can someone try to run this code and identify were is the error!... since I cannot identify were I'm wrong.
The Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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">
<head runat="server">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart(dataValues) {
var data = new google.visualization.DataTable();
data.AddColumn('string', 'Locality');
data.AddColumn('number', 'Frequency');
for (var i = 0; i < dataValues.length; i++) {
data.AddRow(dataValues[i].aString, dataValues[i].anInt);
}
var options = { 'title': 'Pie Chart Test',
'width': 900,
'height': 500
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Items> dataList = new List<Items>();
dataList.Add(new Items("A", 10));
dataList.Add(new Items("B", 20));
dataList.Add(new Items("C", 30));
JavaScriptSerializer jss = new JavaScriptSerializer();
ClientScript.RegisterStartupScript(this.GetType(), "Test", string.Format("<script type=\"text/javascript\">drawVisualization({0});</script>", jss.Serialize(dataList)));
}
}
public class Items
{
public string aString = "";
public int anInt = 0;
public Items(string _aString, int _anInt)
{
aString = _aString;
anInt = _anInt;
}
}
}
Thank You
JavaScript is case sensitive. The method names are .addColumn() and .addRow(), but you are using .AddColumn() and .AddRow(). Check your JavaScript console for errors. You should find a message saying something like undefined is not a function.
The .addRow() method takes an array as its argument, but you are passing in two scalar values. Wrap those up in square brackets: data.addRow([dataValues[i].aString, dataValues[i].anInt]).
You may also run into issues with your use of RegisterStartupScript(). Your startup script may run before the visualization package has finished loading. Instead, I would embed the value in a hidden field on the page and read that value from your script.
<asp:HiddenField runat="server" ID="ChartData" />
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Items> dataList = new List<Items>();
dataList.Add(new Items("A", 10));
dataList.Add(new Items("B", 20));
dataList.Add(new Items("C", 30));
JavaScriptSerializer jss = new JavaScriptSerializer();
this.ChartData.Value = jss.Serialize(dataList);
}
}
function drawChart() {
var dataValues = JSON.parse(document.getElementById("<%= ChartData.ClientID %>").value);
// The rest of the function as written
}
Snippet with all the changes applied:
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataValues = JSON.parse(document.getElementById("ChartData").value);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Locality');
data.addColumn('number', 'Frequency');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].aString, dataValues[i].anInt]);
}
var options = { 'title': 'Pie Chart Test',
'width': 900,
'height': 500
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<input type="hidden" id="ChartData" value="[{"aString":"A","anInt":10},{"aString":"B","anInt":20},{"aString":"C","anInt":30}]" />
<div id="piechart" style="width: 900px; height: 500px;"></div>
I am attempting to use the javascript datepicker to help in showing a calendar and being able to select a date to add/view/edit an event on that date.
I currently have a view that shows the datepicker calender in a div
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Event Calendar</title>
<link rel="stylesheet" href="/Content/themes/base/jquery-ui.css">
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery-ui-1.10.4.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function () {
$("#datepicker").datepicker();
});
</script>
</head>
<body>
Date: <div id="datepicker"></div>
</body>
</html>
I have a model Todays events that will show the events for the day
namespace TryEvents2.Models
{
public class TodaysEventsViewModel
{
public List<Event> events;
}
}
a model for the specific events
namespace TryEvents2.Models
{
[Bind(Exclude = "Id")]
public class Event
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[DisplayName("Start Date")]
public DateTime Start { get; set; }
[DisplayName("End Date")]
public DateTime End { get; set; }
[DisplayName("Event Details")]
public string Message { get; set; }
[DisplayName("User")]
public string UserName { get; set; }
public void setEvent()
{
}
}
}
a model for the database calendar entities
namespace TryEvents2.Models
{
public class CalendarEntities : DbContext
{
public DbSet<Event> Events { get; set; }
}
}
I have a home controller of the following
namespace TryEvents2.Controllers
{
public class HomeController : Controller
{
CalendarEntities db = new CalendarEntities();
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
public PartialViewResult GetWEntitiesByDate(DateTime date)
{
var entities = db.Events.Where(x => x.Start == date.Date);
var todaysEvents = new TodaysEventsViewModel {events = entities.ToList() };
return PartialView("_TodaysEvents", todaysEvents);
}
}
}
I am having difficulties going from here on creating the methods necessary to CRUD the calendar events and the view that would be displaying them. I am wanting to make the standard datepicker element bigger and have a popup window for the event detail display.
Can anyone help with this?
In my few experience doing something like that is quite difficult with jquery UI datepicker. If you want a calendar to works as a datepicker and able to edit events and shows depending on the day I think the best solution for you is Arshaw Fullcalendar
FullCalendar
This is a calendar (not a datepicker) but you can create custom events to make it works as a datepicker-calendar for your purposes. You can choose a date an render your events from a specific date. You are using MVC so for bringing the date you need JSON like this
public ActionResult GetEvents()
{
//code to return the events from DB
return Json(evevtsObject,JsonRequestBehavior.AllowGet);
}
And for the events to load on the calendar you need to call the "events" function from the calendar.
events: function (startdate, enddate, callback) {
var url = "Controller/GetEvents";
$.getJSON(url,
function (result) {
if (result != null) {
for (i in result) {
var calEvent = result[i];
calEvent.startdate = new Date(parseInt(calEvent.startdate.replace("/Date(", "").replace(")/", ""), 10));
calEvent.end = new Date(parseInt(calEvent.enddate.replace("/Date(", "").replace(")/", ""), 10));
}
}
var calevents = result;
callback(calevents);
});
}
Hope this helps.