Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant access Variables in JS/jQuery via <%= variable %>

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?

like image 804
minimen Avatar asked Aug 27 '15 13:08

minimen


People also ask

Can you access the Let variable outside of the block scope in JavaScript?

No, You can't access let variables outside the block, if you really want to access, declare it outside, which is common scope.

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.

Can we access variable outside function in JavaScript?

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.

What is ${ var in JavaScript?

var is the keyword that tells JavaScript you're declaring a variable.


1 Answers

C# code in JS files is not executed - hence the value remains as <%= CurrentUser %>. To do as you require you either need to:

  • Execute this JS code within an ASPX page
  • Make an AJAX request to the server from the JS file which returns the required information.
like image 61
Rory McCrossan Avatar answered Sep 30 '22 06:09

Rory McCrossan