Monzingo Monzingo - 1 month ago 16
Javascript Question

How to use a global variable that is visible by both HTML/Razor and javascript all on the same page

Here is my layout

<html>
@{ bool isAdmin = true; }

if(isAdmin)
{
//the breakpoint hits here
}
</html>

<script type="text/javascript">
function someFunction()
{
if(isAdmin){ //my breakpoint doesnt hit here}
}
$(document).ready(function()
{
@if(isAdmin){ //my breakpoint hits here}
somefunction();
}
</script>


How is it that my global variable is visible from the html/razor within the html and also within the javascript, yet it cannot be seen from the function within the javascript. This doesnt make sense to me. Also if i try something like adding @isAdmin to the function parameter, the error i get is "True is undefined", if i .ToLower() "True", the error is "unexpected token true"

Answer

The reason the second breakpoint hits is because the razor engine recognizes the @if, so your isAdmin is used properly. It appears that using @isAdmin in the JavaScript section will attempt to use the value of your variable as an identifier for a JavaScript variable (I'm not sure if this is really what's happening. After some testing, this appears to be the case; hence, "[value of your variable] is not defined."). Two ways you can get around this:

  1. While writing regular JS, take your isAdmin value as a string, and convert to bool. if (!!"@isAdmin")

  2. Use this syntax to go from razor to JS:

    @if (isAdmin) //razor here { @:console.log('hello!') //@: causes the line to be interpreted as JS. }