I have following code in my index.cshtml where a FoursquareInfo object is beeing created.
#using WebMatrix.Data;
#using CanYouPay.Models.FoursquareAPI;
#{
FoursquareInfo fsInfo = new FoursquareInfo();
Checkins response = new Checkins();
Checkin checkins = new Checkin();
List<RootItem> items = new List<RootItem>();
RootItem item = new RootItem();
Venue venue = new Venue();
Location loc = new Location();
loc.lat = 51.19189444478925;
loc.lng = 4.664656084372357;
venue.location = loc;
item.venue = venue;
items.Add(item);
checkins.items = items;
response.checkins = checkins;
fsInfo.response = response;
}
I have a div in my html code for the index.cshtml where the updateMap(fourSquareInfo) method is called when clicked.
<div id="mapBtn" onclick="updateMap(#fsInfo)" class="btn btn-success btn-lg col-md-2 pull-right">Show Map!</div>
My updateMap function is:
function updateMap(foursquareInfo) {
var uluru = { lat: 20, lng: 30 };
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
Yes, for testing purposes I don't do anything with the foursquareInfo object passed - the lat and long values will be replaced by the foursquareInfo ones when I can fix the error I receive when the onClick event happens:
CanYouPay is not defined at HTMLDivElement.onclick
What is wrong with my html/razor/js code?
As per my comments: Looks like you are trying to pass a c# object into your js - if you view source on that button, it is probably going to be some text including CanYouPay and as you have not defined it as a js variable, it will throw an error, you would either need to create a js object and map your c# object values to it, or pass through a bunch of strings
Option 1 create a js object that matches your c# object and in your razor you can map the values:
<script>
// this needs to be in your razor before the onclick (so object is created before you use it)
var fsJSObject = new fsJSObject(); // this object should match your c# object
fsJSObject.StringValue = '#fsInfo.StringValue'; // this needs to be the final value - eg a string, int, date, etc - cannot be another object, otherwise you will get a similar mistake to above
fsJSObject.IntValue= #fsInfo.IntValue;
// pass fsJSObject into your onclick function
</script>
Option 2, pass the values directly into the function
onclick="updateMap('#fsInfo.StringValue', #fsInfo.IntValue, '#fsInfo.AnotherStringValue')"
Notice the quotes around the string values
When I try to build up the same page using razor I see I get the following in my page:
<div id="mapBtn" onclick="updateMap(WebApplication1.Models.FoursquareInfo)" class="btn btn-success btn-lg col-md-2 pull-right">Show Map!< /div>
As you see Razor will directly set the object which is to say the class name. In this case, I would advise to directly set the location numbers in the call like:
<div id="mapBtn" onclick="updateMap(#loc.lat, #loc.lng)" class="btn btn-success btn-lg col-md-2 pull-right">Show Map!< /div>
And then in the call on the server side build up the object and do what you want with it. Remember you'll have to rebuild the object every time you do a new call to the server: the objects are not kept in memory. It is advised to only put the information in the view that view actually needs instead of your entire serverside object.
Related
When I tried to pass a list to the template I got an error.
The list is defined like:
myList: List<Map<String,int[]>>
Now the data of myList is :
[{First Try=[1,0,0,1], Second Try=[1,1,2,2]}, {}]
I use chart.js to show a chart and so I need a int[] as data list.
my view:
#(myList: List[Map[String,Array[Int]]])
var list = #myList;
for(var i=0;i<list.length;i++){
var map = list[i];
for(var key in map){
myFunction(key,map[key]);
}
}
myFunction(string,array){
//I want directly use the array to the chart’s datasets
//others
var myChart = new Chart(chartid, {
type: 'bar',
data: {
labels: [“a”, “b", “c”, ”s”],
datasets: [{
data: array
}]
}
}
But I got error when I try to traversal the List (The error line shown with Chrome debug)
var out = [{First Try=[I#6e37161d, Second Try=[I#5788d8a9}, {}];
// “Uncaught SyntaxError: Invalid or unexpected token”.
I know when directly output array with
System.out.println(array);
in java it will happen with the string like [I#6e37161d, but I don’t know how to deal with it in javascript.How can I use this array?I will be grateful if anyone can help .
Thank you very much.
You can't convert the Java object directly to a Javascript variable like you're attempting to do.
var list = #myList;
That just takes myList.toString() and attempts to set that as a literal Javascript variable. You need to serialize your Java object to JSON first, then you can parse the JSON in Javascript. Like so:
// Java controller code
String myListJson = Json.stringify(Json.toJson(myList));
// Template
#(myListJson: String)
var list = JSON.parse("#myListJson");
I am not much of a JavaScript expert and trying to figure out here how can I extend an existing object.
HTML:
<li data-brandtarget="Netherlands"><img src="images/netherlands.png" alt="Netherlands">Netherlands</li>
<li data-brandtarget="Netherlands"><img src="images/netherlands.png" alt="Netherlands">Netherlands</li>
JS:
MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet(
// Brand Fetures
new storeLocator.Feature('Aquafleur-YES', 'Aquafleur'),
new storeLocator.Feature('Aquafarm-YES', 'Aquafarm'),
new storeLocator.Feature('Bm_Web-YES', 'Blue Marine'),
// The below mentioned features I want to be added based on a loop
//new storeLocator.Feature('Naamlandnat-Netherlands', 'Netherlands'),
//new storeLocator.Feature('Naamlandnat-Great Britain', 'Great Britain'),
//new storeLocator.Feature('Naamlandnat-France', 'France'),
//new storeLocator.Feature('Naamlandnat-Germany', 'Germany')
);
I am trying to make the country features dynamic. So I am looping through all the lists and getting the attribute. Now while looping how can I extend and add new feature to the existing object? Below is my approach.
jQuery('.country-options li').each(function(){
var countryName = jQuery(this).attr('data-brandtarget');
MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet(
// Country Features
new storeLocator.Feature('Naamlandnat-'+ countryName, countryName)
);
});
I know it is wrong because I guess: I am creating the new object again and again with each loop which overwrites the existing object and thus only the last feature stays in the object.
So what is the right way to extend the features without overwriting the existing feature set here?
I also tried:
by removing the new and keeping it just storeLocator.FeatureSet(...); inside the loop but didn't work.
According to the reference I found, you can call add() on the existing FeatureSet:
MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet();
jQuery('.country-options li').each(function(){
var countryName = jQuery(this).attr('data-brandtarget');
MedicareDataSource.prototype.FEATURES_.add(
new storeLocator.Feature('Naamlandnat-'+ countryName, countryName)
);
});
In asp.net (vb.net) I have a Session variable that contain a HashTable
Dim products As Hashtable = New Hashtable
products("example") = "One product"
Session("products") = products
Now I want to obtain in client side with javascript, the value of products("example").
I try this:
<SCRIPT>
function ShowSessionValue() {
// new object
var sessionHashT = {};
// asign HashTable stored in Session("products") to "sessionHashT"
sessionHashT= '<%=Session("products")%>';
// All alerts show "undefined" (but no errors):
alert(sessionHashT("example"));
alert(sessionHashT(example));
alert(sessionHashT.example);
};
</SCRIPT>
With a breakpoint I see that the value of sessionHashT is :
sessionHashT = 'System.Collections.Hashtable';
How I can get the values of the HashTable with javascript?
Untested, but you could serialize your HashTable to JSON to include in your script:
// assign HashTable stored in Session("products") to "sessionHashT"
sessionHashT= JSON.parse('<%= New JavaScriptSerializer().Serialize(Session("products"))%>');
I suppose you could get away with not parsing it (note the lack of quotes):
// assign HashTable stored in Session("products") to "sessionHashT"
sessionHashT= <%= New JavaScriptSerializer().Serialize(Session("products"))%>;
You should then be able to use the dotted form to access the items by key:
alert(sessionHashT.example);
how to pass parameter from a dataset row value to java function accessed via scripted datasource?
I have a java class that deccrypts an encrypted string
class Decryptor{
public String decrypt(text)
{
.
.
StandardPBEStringEncryptor textEncryptor = new StandardPBEStringEncryptor();
return textEncryptor.decrypt(text);
}
}
I imported it to my birt report that goes like this:
I created a dataset named dsCode with column "code";
open:
sessionUtil = new Packages.com.reports.server.generator.data.SessionUtil();
sessionUtil.openCurrentSession();
c = new Decryptor();
textDecrpt = c.decrypt("O6pas1t9NyY9bmAtjvX2NA==");
fetch;
row["code"] = textDecrpt ;
return true;
this is working fine. however I want to pass a value to the decrypt function from anther dataset row value(encryptedCodecolumn of dsCustomerIfdo). How do I do this? I made the dsCode as datasource of a subreport and I added parameter called pmCode to the dsCode and passed a value to it using "Data Set Parameter Binding"
and made the script like this
textDecrpt = c.decrypt(params["pmCode"]);
this gives me an error end of file undefined.
How do i access a dataset row value in javascript? or pass a rowvalue of a dataset to a script function?
this is not working
var dset = reportContext.getDesignHandle().findDataSet("dsCustomerInfo");
textDecrpt = c.decrypt(dset.getRow("encryptedCode").value);
thanks
I solved it by not using another dataset like what I intially tried. Just used the dsCusotmerInfo, added a computed column called decryptedCode and added the scirpt on fetch on it. This decrypts all code of all customers.
sessionUtil = new Packages.com.reports.server.generator.data.SessionUtil();
sessionUtil.openCurrentSession();
c = new Decryptor();
row["decryptedCode"] = c.decrypt(row["encryptedCode"]);
return true;
I'm trying to do something very simple with javascript but can't quite get my head around it. I'm not sure what format I should be passing the var address as.
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(address);
});
});
function getMap(address) {
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(address),
...
});
}
I'm getting an error when I pass the JQuery ref to normal javascript: TypeError: 'undefined' is not an object (evaluating 'a.position=b'). Any help appreciated.
If I read this correctly and you posted this code correctly, you pass a non-existing object lasting to getMap(), while you want to pass the address object. What happens if you correct this?
jQuery instances are just normal javascript objects like all others, so there should not be a problem.
You're passing the variable latLng to getMap, but its value isn't set. Your ready function at the top should look like this:
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(this);
});
});
Or, if you're trying to pass the address variable you set, make your ready function look like this:
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(address);
});
});
Your issue has nothing to do with jquery or javascript.
You are passing the wrong data into the LatLng method.
You need to pass in two parameters to the LatLng method:
...
var mapDiv = $('#mapDiv')[0], // also make sure the div is a regular dom node
lat = 7.1011123,
lng = 4.6667566;
function getMap(address) {
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng( lat, lng ), // you must pass in two parameters
...
});
}
If you are trying to get your LatLng coords from a text div then you need to convert your strings into floats.
Supposing the following html is what you use:
<ul>
<li class="latlng">7.4142335,3.1296874</li>
<li class="latlng">8.4135039,-5.1256828</li>
<li class="latlng">-14.4101158,-5.2810335</li>
</ul>
Then this would be the function running getMap() for every .latlng list item:
$('.latlng').each(function( i ){
var address = $(this).text();
address = address.split(','); // convert your text into an array
// send in your lat and lng strings parsed as floats
getMap(
parseFloat( address[0] ),
parseFloat( address[1] )
);
});