在javascript脚本块中计算Razor@Request.IsLocal
我在javascript块中使用了以下Razor语句,但出现了get“True is undefined”运行时错误。@Request.IsLocal呈现为布尔值True。多谢各位在javascript脚本块中计算Razor@Request.IsLocal,javascript,asp.net-mvc,razor,Javascript,Asp.net Mvc,Razor,我在javascript块中使用了以下Razor语句,但出现了get“True is undefined”运行时错误。@Request.IsLocal呈现为布尔值True。多谢各位 var检验; 如果(@Request.IsLocal | |@Request.IsLocal=='True') { 测试=‘本地’; } 其他的 { 测试='非本地' } 警报(测试); True不是javascript布尔值。它是true 试着跟随 <script type="text/javascrip
var检验;
如果(@Request.IsLocal | |@Request.IsLocal=='True')
{
测试=‘本地’;
}
其他的
{
测试='非本地'
}
警报(测试);
True
不是javascript布尔值。它是true
试着跟随
<script type="text/javascript">
var test;
if ("@(Request.IsLocal)" == 'True')
{
test = 'local';
}
else
{
test = 'not loccal'
}
alert(test);
</script>
var检验;
如果(“@(Request.IsLocal)”=“True”)
{
测试=‘本地’;
}
其他的
{
测试='非本地'
}
警报(测试);
或
var检验;
if(@Request.IsLocal.ToString().ToLowerInvarient())
{
测试=‘本地’;
}
其他的
{
测试='非本地'
}
警报(测试);
当razor执行当前代码时,它会产生如下输出
var test;
if (True || True == 'True')
{
test = 'local';
}
else {
test = 'not loccal';
}
假设Request.IsLocal
返回true
浏览器将尝试执行此操作。现在javascript框架认为True
是一个js变量,但它没有在任何地方定义。两者都不是布尔值true
(javascript区分大小写)。所以浏览器会抱怨
未定义True
您可以通过简单地切换到在服务器上执行的三元运算符表达式并将值返回到测试变量来简化代码
这应该行得通
<script type="text/javascript">
var test= '@(Request.IsLocal?Html.Raw("local"):Html.Raw("not local"))';
alert(test);
</script>
var test='@(Request.IsLocal?Html.Raw(“本地”):Html.Raw(“非本地”));
警报(测试);
如果检查页面的视图源,可以看到没有If条件,因为这些条件是在服务器上执行的
<script type="text/javascript">
var test= '@(Request.IsLocal?Html.Raw("local"):Html.Raw("not local"))';
alert(test);
</script>