javascript - jquery中if语句的问题

标签 javascript jquery asp.net-mvc

我有一个非常简单的应用程序。我的 Home Controller 接收 Comment 对象并运行其逻辑以确定是否需要显示通知。如果答案是肯定的,那么它会在 ViewBag 中设置以下参数:

ViewBag.toDisplayNotification = 1;
ViewBag.notificationTitle = "This is the title";
ViewBag.notificationId = 2;

否则,它会按如下方式设置参数(我随机将所有内容设置为 null,以便 toDisplayNotification 不再为 1!)

ViewBag.toDisplayNotification = null;
ViewBag.notificationTitle = null;
ViewBag.notificationId = null;

然后它显示评论部分 View ,其中我有:

<script>
    $(function myfunction() {

        var toDisplayNotification = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.toDisplayNotification));
        var notificationTitle = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.notificationTitle));
        var notificationId = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.notificationId));

        if(toDisplayNotification == 1){
            var n = new Notification(notificationTitle, {
                body: "This is where the body goes",
                icon: '@Url.Action("GetImageByNotificationId", "Image", new { id = ViewBag.notificationId})'
            });
        }
    });
</script>

所以我面临的问题是,无论 toDisplayNotification 值如何, View 始终显示通知(我已经测试了 Home Controller 的逻辑,并且知道它为每个 ViewBag 属性设置了正确的值),即使toDisplayNotification 的值不应为零。

我的 ViewBag 值是否可能以某种方式发生更改(不能来自代码,因为我的 Home Controller 直接显示部分 View ,因此值在转换中应保持不变)或者我是否在 if 条件中遗漏了某些内容?

<小时/>

编辑 1 - 回答以下一些问题。我只使用 Newtonsoft.Json.JsonConvert.SerializeObject 因为有人在不同的问题中建议我使用。否则,我不是序列化专家(我发现除非我序列化属性,否则我无法将非整数值从 ViewBag 提取到 jquery/javascript 中)。

此外,我确实尝试用以下任一内容替换 toDisplayNotification 行,但都不起作用:

var toDisplayNotification = @ViewBag.toDisplayNotification;
//or 
var toDisplayNotification = @Html.Raw(ViewBag.toDisplayNotification);

最佳答案

试试这个

   var toDisplayNotification = @Html.Raw(ViewBag.toDisplayNotification);
   if(toDisplayNotification == 1){
        var n = new Notification(notificationTitle, {
            body: "This is where the body goes",
            icon: '@Url.Action("GetImageByNotificationId", "Image", new { id = ViewBag.notificationId})'
        });
    }

我不完全确定为什么要序列化 ​​ViewBag.toDisplayNotification 然后将其与数字进行比较。

关于javascript - jquery中if语句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41972069/

相关文章:

javascript - 对于类 'y' 的每个表,如果表不包含类 'x' 的后代,则选择 th 和 td 后代

javascript - 在元素上设置验证样式

javascript - jQuery 可拖动可滚动容器

javascript - 如何将使用 javascript 创建的 div 传递到另一个使用 php 的页面

javascript - 仅用 javascript css 和 html 编写的可编辑表格

javascript - 函数的返回未分配给 $scope?

jquery - .load 正在执行 post 而不是 get

javascript - 强制单页应用程序仅在一个选项卡中使用的惯用方法

asp.net-mvc - Visual Studio - 预编译 - 无点

asp.net - 使用连接服务访问 ASP.NET Core 应用程序中的 Azure 存储