I'm trying to access a asp.net variable (c#) from JavaScript/jQuery.
I've found a solution, here and here. But unfortunately these are not working for me.
Here's a snippet:
Default.aspx.cs
public partial class Default : System.Web.UI.Page
{
public string CurrentUser { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
CurrentUser = User.Identity.Name.Split('\\')[1]; //I need the value of "CurrentUser"
}
...
}
script.js
$(document).ready(function (){
var _currentUser = "<% =CurrentUser %>"; // e.g. _currentUser = "minimen"
...
});
_currentUser's value is always "<% =CurrentUser %>".
Any ideas?
No, You can't access let variables outside the block, if you really want to access, declare it outside, which is common scope.
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.
Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.
var is the keyword that tells JavaScript you're declaring a variable.
C# code in JS files is not executed - hence the value remains as <%= CurrentUser %>
. To do as you require you either need to:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With