在JavaScript中评估Razor变量

4

我需要在JavaScript函数中评估剃刀变量。给定以下代码:

 @{var unseenNotificationsExist = false;}
 
 @foreach(var notification in viewModel)
 {
    if (notification.WasSeen == false)
    {
      unseenNotificationsExist = true;
      break;
    }
 }

我需要像这样在JavaScript中评估unseenNotificationsExist变量:
 if(@unseenNotificationsExist == true)
        $('#unseenNotifCount').addClass('notifNotSeen');

然而,在我调试JavaScript代码时,我得到了这个:
if(True == true)

我还遇到了以下错误:

未捕获的ReferenceError:True未定义

6个回答

5
var unseenNotificationsExist = @(unseenNotificationsExist?"true":"false") ;
//the line above must be part of your view

if(unseenNotificationsExist === true)
        $('#unseenNotifCount').addClass('notifNotSeen');
//this can be part of your js file or alternatively and less 
//preferably part of your view

它也可以在视图中包含javascript片段中的所有代码。 - Octavian Epure

4
我找到了一个解决方法:我添加了这个。
var True = true

现在,在JavaScript中定义了一个变量“True”,并且评估结果为True == true,其返回true。

2

每当我想将模型数据转换为JSON对象或JSON变量时,我更喜欢使用Json.Encode

将模型的对象(dto)转换为JavaScript

var accountDto = @Html.Raw(Json.Encode(@Model.AccountDto))

将模型的一个布尔属性转换为中文:
var isTrue = @Json.Encode(Model.IsTrue)

0
如果你不想呈现JavaScript,请使用Daniele的建议。
如果您坚持在JavaScript中进行比较:
if(@unseenNotificationsExist.ToString().ToLower() === true)

虽然这可能有效,但最好的做法是自己将变量转换为JavaScript,然后进行操作。仅依赖ToString()不是一个好选择。 - Parv Sharma
1
此类模式也不允许用户将所有的JS代码分离到单独的文件中。 - Parv Sharma
这不是一个很好的解决方案,同意吗!但你的解决方案也不允许单独的JS文件... ;-) 编辑:事实上,我撤回之前的话 - 你肯定只是在提到“if”部分。 - UweB
为什么不直接定义一个全局变量呢?我已经编辑了我的回答,请再次检查。 - Parv Sharma
是的,我现在看到了,当我发布时它并不在那里,但最终我想出来了。 - UweB

-1

你尝试过:

if('@unseenNotificationsExist' === 'True')
        $('#unseenNotifCount').addClass('notifNotSeen');

它仍将保持为True而不是true。 - Parv Sharma
是的,我做了,结果一样。 - Octavian Epure
在我看来,它只是缺少一个 @if 前面,可能还需要花括号来使其成为 C#-if - UweB
if语句在JavaScript中,而不是Razor。 - Daniele

-1

尝试使用

if('@unseenNotificationsExist')

我的回答不完整,我进行了编辑。这对我来说似乎有效。 - Alexandru Marculescu
这会进入true块,因为在js中无论你检查if(“True”)还是if(“False”),都不重要。 - Parv Sharma
正确。你不能用false来初始化变量,只能声明它。 - Alexandru Marculescu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接