Hi I have a Session Provider class to handle Sessions in my MVC application.
Here is the Session Provider Class...
public class SessionProvider
{
public static Portal.Application.BoundedContext.ScreenPop.Dtos.User LoggedUser
{
get { return (Portal.Application.BoundedContext.ScreenPop.Dtos.User) HttpContext.Current.Session["LoggedUser"]; }
set { HttpContext.Current.Session["LoggedUser"] = value; }
}
public static void Clear()
{
HttpContext.Current.Session.Abandon();
HttpContext.Current.Session.Clear();
}
}
And the User class which used to cast the above Session has these attributes.
Name
PhoneNumber
I need to get these Name and Phone number in my View using javascript..
Here what I have dobe so far...
<script type="text/javascript">
#{
User loggedUser = SessionProvider.LoggedUser;
}
var loggedUserName = loggedUser.Name ;
var loggedUserPhone = loggedUser.PhoneNumber;
</Script>
But I have this error in firebug when I run my application..
ReferenceError: loggedUser is not defined
var loggedUserName = loggedUser.Name;
How can I get those two values?
I am using Razor View engine...
It should be like following
<script type="text/javascript">
#{
User loggedUser = SessionProvider.LoggedUser;
}
var loggedUserName = "#loggedUser.Name" ;
var loggedUserPhone = "#loggedUser.PhoneNumber";
</Script>
The code you wrote will try to access the Server side object in Javascript which is not at all possible. Your client script doesn't have any idea about your server side declared variables hence it will throw an error. Hence you have to print the property value with the help of razor and use that as string in your javascript code.
Try this;
<script type="text/javascript">
#{
User loggedUser = SessionProvider.LoggedUser;
}
var loggedUserName = "#(loggedUser.Name)" ;
var loggedUserPhone = "#(loggedUser.PhoneNumber)";
</Script>
Following post will help you to understand the correct syntax.
Razor’s #: and <text> syntax
I believe this should do it #: escapes razor.
<script type="text/javascript">
#{
User loggedUser = SessionProvider.LoggedUser;
#:var loggedUserName = loggedUser.Name;
#:var loggedUserPhone = loggedUser.PhoneNumber;
}
</Script>
However you could read your cookies via JS.
var the_cookie = document.cookie;
Related
I'm trying to pass var 'id' from the page 'a.html' to 'b.html'. The var content comes from 'code.gs' as below:
code.gs
function data(){
var id = 1;
return id;
}
Next, I get this var and I show it in 'a.html':
a.html
<?
var id = data();
?>
<h1><?= id ?></h1>
Go to B.html
By clicking 'Go to B.html', the system directs the user to there. I need to bring the same value of var 'id' from the page 'a.html' to 'b.html'.
Ps: searching for a little, I saw that there's a kind to send this var by the command 'localStorage', but it's not working for me. :(
Can anybody help me?
Use localstorage
a.html
localStorage.setItem('id',1)
b.html
var id = localStorage.getItem('id')
the other way is to put it in a js file and import it in both html
Storing & Retrieving html data on the server
Client Side JavaScript:
<script>
function saveId(v) {
google.script.run.saveKeyValue({key:'id',value:v});
}
function getId() {
google.script.run
.withSuccessHandler(function(v){
alert('The value is ' + v );
})
.getKeyValue('id');
}
</script>
Server Side Google Apps Script:
function saveKeyValue(obj) {
PropertiesService.getScriptProperties().setProperty(obj.key,obj.value);
}
function getKeyValue(key) {
return PropertiesService.getScriptProperties().getProperty(key);
}
You could also replace PropertiesService with CacheService.
Client To Server Communications
Properties Service
So I want to store the session in jquery. export_type is storing all the ids which is checked via checkbox I want to store all those ids in the session. Following is my code , But I have Uncaught SyntaxError: Invalid or unexpected token error. Any help will be appreciated. thanks in advance.
$("#export").click(function () {
var id = [];
$(':checkbox:checked').each(function (i) {
id[i] = $(this).val();
});
var export_type = id;
var set_session = "<?php $this->session->set_userdata('export_type', export_type); ?>";
export_php();
});
Javascript cannot read PHP. What you will have to do is to have your script make a separate request to a CodeIgniter controller.
Javascript:
$.get("export/set_session/" + export_type, function (result) {
console.log(result);
})
PHP (application/controllers/Export.php):
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Export extends CI_Controller {
public function set_session($export_type)
{
$this->session->set_userdata('export_type', $export_type);
echo 'Session set!';
return;
}
}
if your above javascript code lies in the view file as inline javascript inside a script tag then it is should be fine but, if this code is inside in a different javascript file then it will not work.
There is a web page. In page source have script:
<script>
var important = [{....}];
</script>
How get information from this variable with use node.js???
In a similar situation, when information was in function:
$(function() {
_very.important ([{....}]);
I use code:
var cloudscraper = require("cloudscraper");
cloudscraper.get("link" , function(error, response, data) {
if (error) {
console.log('ERRRRRRROR');
} else {
var info = JSON.parse(data.split("_very.important(")[1].split(")")[0]);
But, I dont know how work with this problem.
var important = [{....}];
You can assign a id to the script like <script id="script"> and get the details through innerHTML like
document.getElementById('script').innerHTML
since i didn´t find any solution that helped me, i thought i asked.
I need a JavaScriptfunction with calls a method in my code-behind, and since i´m really new to this, i dont understand what am i doing wrong.
On my Master Page (Site.Master) i enabled PageMethods:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
And in the Content of my Page i have put the Script:
function reply_click(clicked_id) {
alert(clicked_id);
PageMethods.javascriptTest(clicked_id);
And now my method in the code-behind:
[WebMethod]
public void javascriptTest(int buttonID)
{
Test2.Text += buttonID + "***";
// Use the ID for DB access
}
I need that ID for later, when i have to do stuff in my database, but i´m always getting PageMethods undefined errors and i dont know why :/
EDIT: The Solution was indeed to make the WebMethod static, i just made a workaround, so i could use all the details i need for my db access
JavaScript:
function reply_click(clicked_id, clicked_name) {
// Schulungsdaten holen
var grid = document.getElementById("<%= SignGridView.ClientID %>");
var row = grid.rows[0];
var appointmentData = row.cells[clicked_id].innerText;
// Userdaten holen
var userID = document.getElementById("<%= UserData.ClientID %>").innerText;
PageMethods.javaScriptUserSignIn(appointmentData, userID, clicked_name, OnSucceeded, OnFailed);
location.reload();
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
Code-Behind:
[WebMethod]
public static string javaScriptUserSignIn(string appointmentData, string userID, string status)
{
string result = "";
SignIn sign = new SignIn();
result = sign.SignToTraining(appointmentData, userID, status);
return result;
}
Your javascriptTest method needs to be static
Try This:
[System.Web.Services.WebMethod]
public static void javascriptTest(int buttonID)
{
Test2.Text += buttonID + "***";
// Use the ID for DB access
}
I keep getting this error in my JavaScript no matter what fix I try. It's almost as if $.connection is not being recognized even though I have all the SignalR JavaScript libraries in place in my _layout. I get the following error in the Chrome browser console:Uncaught TypeError: "Cannot read property 'multipleFileHub' of undefined Index:508
(anonymous function) Index:508
x.event.dispatch jquery-2.0.2.js:4692
y.handle jquery-2.0.2.js:4376" of undefined".
Does it matter that my Global.asax inherits from "StsMvcHttpApplication" rather than the standard "System.Web.HttpApplication"? And in my case, I have to put the "RouteTable.Routes.MapHubs();" in my "RegisterRoutes" method rather than "Application_Start" since Application_Start doesn't fire fast enough... it starts hunting for controllers if I put it in the app start.
Would appreciate the help! I'll show the layout code first and then all the separate pieces of code:
_LAYOUT
#section head
{
#Scripts.Render("~/Scripts/Libs/jquery-2.0.2.min.js")
#Scripts.Render("~/Scripts/Libs/jquery-ui-1.10.3.min.js")
#Scripts.Render("~/Scripts/Libs/jquery.validate.min.js")
#Scripts.Render("~/Scripts/Libs/jquery.validate.unobtrusive.min.js")
#Scripts.Render("~/Scripts/Libs/modernizr-2.6.2.js")
#Scripts.Render("~/Scripts/Libs/modernizr.custom.blobconstructor.js")
#Scripts.Render("~/Scripts/SidebarMenu.js")
#Scripts.Render("~/Scripts/BC_Common.js")
#Scripts.Render("~/Scripts/scene.layoutservice.js")
#Scripts.Render("~/Scripts/scene.dataservice.js")
#Scripts.Render("~/Scripts/jquery.signalR-1.1.2.min.js")
#Scripts.Render("~/signalr/hubs")
#Scripts.Render("~/Scripts/scene.startup.js")
}
INDEX.CSHTML
$('#dBtn').click(function () {
var docIds = sceneLayoutService.getSelection();
if (docIds.length === 0) {
alert("you need to select one");
return false;
} else {
var docIdsParam = jQuery.param(docIds.map(function (value) {
return { "name": "docIds", "value": value };
}));
// Proxy created on the fly
var test_connection = $.connection.multipleFileHub;
// Start the connection
$.connection.hub.start().done(function() {
test_connection.server.send("test");
});
}
return true;
});
SERVER CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace Portal.Web.Hubs
{
[HubName("multipleFileHub")]
public class multipleFileHub : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.All.addMessage(message);
}
}
}
GLOBAL.ASAX ROUTING
public static void RegisterRoutes(RouteCollection routes)
{
RouteTable.Routes.MapHubs();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
routes.Ignore("{*allpng}", new { allpng = #".*\.png(/.*)?" });
routes.Ignore("{*allgif}", new { allgif = #".*\.gif(/.*)?" });
routes.Ignore("{*alljpg}", new { alljpg = #".*\.jpg(/.*)?" });
routes.MapRoute(
"Error", // Route name
"Error/{action}/{id}", // URL with parameters
new {controller = "Error", action = "Index", id = UrlParameter.Optional });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Landing", id = UrlParameter.Optional } // Parameter defaults
);
}
ALL JAVASCRIPT REFERENCES ON THE PAGE
<script src="/ConnectPortal/Scripts/Libs/jquery-2.0.2.min.js"></script>
<script src="/ConnectPortal/Scripts/Libs/jquery-ui-1.10.3.min.js"></script>
<script src="/ConnectPortal/Scripts/Libs/jquery.validate.min.js"></script>
<script src="/ConnectPortal/Scripts/Libs/jquery.validate.unobtrusive.min.js"></script>
<script src="/ConnectPortal/Scripts/Libs/modernizr-2.6.2.js"></script>
<script src="/ConnectPortal/Scripts/Libs/modernizr.custom.blobconstructor.js"></script>
<script src="/ConnectPortal/Scripts/SidebarMenu.js"></script>
<script src="/ConnectPortal/Scripts/BC_Common.js"></script>
<script src="/ConnectPortal/Scripts/scene.layoutservice.js"></script>
<script src="/ConnectPortal/Scripts/scene.dataservice.js"></script>
<script src="/ConnectPortal/Scripts/jquery.signalR-1.1.2.min.js"></script>
<script src="/ConnectPortal/signalr/hubs"></script>
<script src="/ConnectPortal/Scripts/scene.startup.js"></script>
It turns out the cause of this issue was because the jquery library was being loaded on the page a second time. There was another javascript library being used in the layout that was inserting the non-minified jquery library on the page after the first minified one. It was hard to find this since the code to insert the other jquery library was not displayed on the layout page. Anyway, just thought I'd let all who read this know that the issue is DEFINITELY related to the jquery library being added after the signalR library.
David Fowler, from the above comments, was spot on! Thanks!