如何使用一个全局变量,这是可见的HTML/Razor和javascript都在同一个页面上



这是我的布局

<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>

我的全局变量是如何从html/razor在html和javascript中可见的,但它不能从javascript中的函数中看到。这对我来说没有意义。此外,如果我尝试添加@isAdmin到函数参数,我得到的错误是"True is undefined",如果i .ToLower()"True",错误是"unexpected token True"

第二个断点击中的原因是因为razor引擎识别了@if,因此您的isAdmin被正确使用。似乎在JavaScript部分使用@isAdmin将尝试使用变量的值作为JavaScript变量的标识符(我不确定这是否真的发生了什么)。经过一些测试,情况似乎是这样;因此,"[变量的值]没有定义。")。有两种方法可以解决这个问题:

  1. 在编写常规JS时,将isAdmin值作为字符串,并转换为bool。if (!!"@isAdmin")

  2. 使用下面的语法从razor切换到JS:

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

确保调用了函数

<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>

最新更新