ArmandoS63
ArmandoS63

Reputation: 703

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?

Upvotes: 5

Views: 240

Answers (3)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

You should be injecting any values you need for client-side use into the page, not into the JavaScript. If you use clever script techniques (e.g. generate a JS file from a view), you void all possible caching of the "page" (script) which has serious implications for commercial deployment of a website.

Typically you would use an input type="hidden" or inject data- attribute values into a key DOM element (like body). You can pick them up very simply from JavaScript/jQuery:

1. Hidden field

e.g. for a hidden field with id="currentuser"

HTML:

<input id="currentuser" type="hidden" value="<% =CurrentUser %>"/>

JQuery:

$(document).ready(function (){
    var _currentUser = $('#currentuser').val();
    ...
});

2. data- attribute

or add the value as a data- attribute on a key DOM element e.g. on the body element

HTML:

<body data-currentuser="<% =CurrentUser %>">

JQuery:

$(document).ready(function (){
    var _currentUser = $('body').data('currentuser');
    ...
});

3. Inject global variable in the page

Worst-case, have a small snippet of Javascript at the top of the page that injects a global variable value:

HTML:

<script>
    window.currentuser="<% =CurrentUser %>";
</script>

JQuery:

$(document).ready(function (){
    var _currentUser = window.currentuser; // or just currentuser
    ...
});

I use this last technique in my Razor layout file for one simple purpose only. Injecting the site root URL on the current website, so that it is available for any relative Ajax calls:

e.g. in Razor layout file

<script>
    window.siteRoot="@Url.Content("~/")";
</script>

Upvotes: 2

Nikhil Vartak
Nikhil Vartak

Reputation: 5117

You cannot access the page fields from within a separate script file. Put your code in head element of Default.aspx and it will work.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 3

Related Questions