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

I am trying to access an asp.net (C #) variable from JavaScript / jQuery.

I found a solution, here and here . But unfortunately this does not work for me.

Here is 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 %>"; // eg _currentUser = "minimen" ... }); 

_currentUser value is always "<% = CurrentUser%>".

Any ideas?

+5
source share
3 answers

You must enter any values ​​necessary for use on the client side, on the page, and not in JavaScript. If you use clever script methods (for example, generate a JS file from a view), you will invalidate all possible caching of the "page" (script), which has serious consequences for the commercial deployment of the website.

Usually you should use the input type="hidden" or enter the values ​​of the data- attribute in a key DOM element (for example, body ). You can simply select them from JavaScript / jQuery:

1. Hidden field

eg. 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 a value as a data- attribute to a key DOM element, for example. on the body element

HTML:

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

JQuery

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

3. Entering a global variable on the page

In the worst case, there is a small Javascript snippet at the top of the page that introduces the value of the global variable:

HTML:

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

JQuery

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

I use this latest technique in my Razor layout file for just one simple purpose. Embed the root URL of the site on the current website so that it is accessible to any relative Ajax calls:

eg. in the Razor layout file

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

C # code in JS files is not executed - so the value remains as <%= CurrentUser %> . To do what you need, you need:

  • Run this js code on an aspx page
  • Make an AJAX request to the server from a JS file that returns the required information.
+3
source

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

0
source

All Articles