Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variable from code behind via javascript

I have the following code that I want to return to a variable "t" in javascript:

Code behind:

Public Shared Function GetSomeText() As String
  Dim result = "This is from code behind"
  Return result
End Function

Caller variable in javascript:

//This is not working like that, I think
    var t = GetSomeText();

So, how can I make variable "t" get the "result" from Function GetSomeText from code-behind?

Thank you.

like image 968
Narazana Avatar asked Apr 26 '10 15:04

Narazana


People also ask

How do you access variables in JavaScript?

In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting.

How can access JavaScript variable in asp net code behind?

You cannot directly access the javascript variables in your code behind. You'd need to send the information to the server, for example by sending them back as form fields or query string parameters via an ajax request.

Can you access a variable inside a function JavaScript?

JavaScript has function scope: Each function creates a new scope. Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with var , let and const are quite similar when declared inside a function.


1 Answers

Try this -- assuming that this a public method on the page. This will call the method GetSomeText() on the page class and then do a Response.Write() of the data to the page as it's being rendered. The result should end up between the single quotes in your javascript.

 var t = '<%= GetSomeText() %>';
like image 100
tvanfosson Avatar answered Sep 18 '22 12:09

tvanfosson