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>