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


here 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 global variable visible html/razor within html , within javascript, yet cannot seen function within javascript. doesnt make sense me. if try adding @isadmin function parameter, error "true undefined", if .tolower() "true", error "unexpected token true"

the reason second breakpoint hits because razor engine recognizes @if, isadmin used properly. appears using @isadmin in javascript section attempt use value of variable identifier javascript variable (i'm not sure if what's happening. after testing, appears case; hence, "[value of variable] not defined."). 2 ways can around this:

  1. while writing regular js, take isadmin value string, , convert bool. if (!!"@isadmin")

  2. use syntax go razor js:

    @if (isadmin) //razor here { @:console.log('hello!') //@: causes line interpreted js. }


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -