I've been trying to pass an ASP.NET variable to a javascript function without any luck so far.
What I have is:
A master page that is using several .js files under folder root/js
I'm trying to create a public variable that contains the username of a person and would like to send it to a function that is inside one of the js files mentioned above.
public string username;
...
username = User.Identity.Name.ToString();
my js is:
$(document).ready(function {
var username = "<%= username %>";
var element = document.getElementById("userid");
element.innerHTML = username; });
After executing this I get <%= username %> and not the actual value.
I tried a second approach:
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "customScript", "AssignValue('" + username + "');", true);
but I get function (e,t){return new x.fn.init(e,t,r)} as a result... I don't know what to do.
Any ideas will be highly appreciated!
Thank you!
// aspx
<asp:HiddenField runat="server" ID="hfUserName" />
// page_load:
hfUserName.Value = username;
// js
$(function() {
$("#userid").text($("input[id$='hfUserName']").val());
});
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
Hi I worte a js client side and rendered that server side aswell when i user filling the form the Username field need to be simultaneously filled based on Email input before submiting the form.
My query is in the Email field and Username field the values "UserName"
and "Email" are appearing by Default and also i cant edit the email field the forms is able to submit with valuse UserName and Email which is not i am looking.
the below code is my client side JS
<asp:TextBox ID="Email" runat="server" onkeyup="change();"></asp:TextBox>
function change(){
document.getElementById('ctl00_ctl40_g_e7fed4bf_b25a_4a8a_943d_e31932556a9e_FBACreateUserWizard_CreateUserStepContainer_UserName').value = 'UserName';
document.getElementById('ctl00_ctl40_g_e7fed4bf_b25a_4a8a_943d_e31932556a9e_FBACreateUserWizard_CreateUserStepContainer_Email').value = 'Email';
UserName.value=Email.value;
}
The below is my C# which i used stringbuilder
protected override void RenderContents(HtmlTextWriter writer)
{
System.Text.StringBuilder sb2 = new System.Text.StringBuilder();
sb2.AppendLine(#"<script language='javascript'>");
sb2.AppendLine(#"function change(){");
sb2.AppendLine(#"var Email= document.getElementById('#ctl00_ctl40_g_e7fed4bf_b25a_4a8a_943d_e31932556a9e_FBACreateUserWizard_CreateUserStepContainer_Email');");
sb2.AppendLine(#"var UserName= document.getElementById('#ctl00_ctl40_g_e7fed4bf_b25a_4a8a_943d_e31932556a9e_FBACreateUserWizard_CreateUserStepContainer_UserName');");
sb2.AppendLine(#"UserName.value=Email.value;");
sb2.AppendLine(#" }");
sb2.Append(#"</script>");
if (!Page.ClientScript.IsStartupScriptRegistered("JSScript"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "JSScript", sb2.ToString());
}
The reason i added my code into C# stringbuilder is i am unable to get the java code on clientside when checked using f12 i am not able to see any of the java code which i wrote on aspx page so i used string builder to get that code.
Thanks
I managed to fix the issue.
I have used the below code
function change() {
var Email = document.getElementById('ctl00_ctl40_g_e7fed4bf_b25a_4a8a_943d_e31932556a9e_FBACreateUserWizard_CreateUserStepContainer_Email');
var UserName = document.getElementById('ctl00_ctl40_g_e7fed4bf_b25a_4a8a_943d_e31932556a9e_FBACreateUserWizard_CreateUserStepContainer_UserName');
UserName.value = Email.value;
}
System.Text.StringBuilder sb2 = new System.Text.StringBuilder();
sb2.AppendLine(#"<script language='javascript'>");
sb2.AppendLine(#"function change(){");
sb2.AppendLine(#"var Email = document.getElementById('ctl00_ctl40_g_e7fed4bf_b25a_4a8a_943d_e31932556a9e_FBACreateUserWizard_CreateUserStepContainer_Email');");
sb2.AppendLine(#"var UserName = document.getElementById('ctl00_ctl40_g_e7fed4bf_b25a_4a8a_943d_e31932556a9e_FBACreateUserWizard_CreateUserStepContainer_UserName');");
sb2.AppendLine(#"UserName.value=Email.value;");
sb2.AppendLine(#" }");
sb2.AppendLine(#"</script>");
if (!Page.ClientScript.IsStartupScriptRegistered("JSScript"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "JSScript", sb2.ToString());
}
Thanks
I'm trying to use flask with url_for. The problem is that when I try to launch an alert with the value of the javascript variable everything seems ok, but when I try to launch a alert with the url_for the content of the variable is not printed. What I'm doing wrong? or What is missing in my code?
How can I pass a JavaScript variable into the url_for function?
html code:
<a class="dissable_user_btn" data-user_id="{{user.id}}" href="#" title="Change Status"><i class="fa fa-plug"></i>
</a>
JS Code:
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id) //everything ok
alert ('{{url_for('.dissable', _id=user_id)}}'); //dont print the valur of user_id
</script>
Short answer: you can't. Flask & Jinja2 render the template on the server side (e.g. Flask is translating all of the {{ }} stuff before it sends the HTML to the web browser).
For a URL like this where you're including a variable as part of the path you'd need to build this manually in javascript. If this is an XHR endpoint I'd recommend using GET/POST to transfer the values to the server as a better best practice than constructing the URL this way. This way you can use Jinja:
$(document).ready(function(){
var baseUrl = "{{ url_for('disable') }}";
$('.dissable_user_btn').click(function(event) {
var user_id = $(this).data("user_id");
// first part = url to send data
// second part = info to send as query string (url?user=user_id)
// third parameter = function to handle response from server
$.getJSON(baseUrl, {user: user_id}, function(response) {
console.log(response);
});
});
});
I found another solution for this. My problem started when I needed to pass a variable with space.
First I created a function to remove trailing and leading spaces
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
After that, I used the function and encoded the URL
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id)
user_id = strip(user_id).replace(" ","%20");
alert ('{{url_for('.dissable', _id='user_id')}}.replace('user_id',user_id);
</script>
It worked pretty nice for me!
This is how I applied to my problem
<script>
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
$(document).ready(function() {
$('#exportcountry').click(function() {
var elemento = document.getElementById("countryexportbtn");
var country = strip(elemento.textContent).replace(" ","%20");
$('#exportevent').load("{{ url_for('get_events',country = 'pais') }}".replace('pais',country));
});
});
</script>
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
}
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;