2017-02-01 52 views
0

我有一個非常簡單的應用程序。我的主控制器收到一個Comment對象並運行其邏輯以確定是否需要顯示通知。如果答案是肯定的,那麼就設置以下參數ViewBag:問題與if語句在jquery

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

一樣,它設置參數如下(我隨機設置一切null,以toDisplayNotification不會是1了!)

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

然後,它顯示了註釋局部視圖中,我有:

<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價值,始終顯示即使toDisplayNotification的值不爲0,通知(我測試了我的Home控制器的邏輯並知道它爲每個ViewBag屬性設置了正確的值)。

是否有可能我的ViewBag值以某種方式被改變(不能從代碼,因爲我的Home控制器直接顯示部分視圖,所以值應該保持不變的過渡)還是我錯過了我的東西if條件?


編輯1 - 回答下面的一些問題。我只使用Newtonsoft.Json.JsonConvert.SerializeObject,因爲在另一個問題中有人建議我使用。否則,我不是一個序列化專家(我發現,除非我序列化屬性,我不能從ViewBag中取出非整數值到jquery/javascript中)。

而且,我也嘗試用任意更換以下的toDisplayNotification線,但沒有一個工作:

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

你在哪裏調用'myfunction()'? (並注意,你可以使用'var notificationTitle ='@ ViewBag.notificationTitle'') –

+0

如果你console.log(toDisplayNotification)它看起來像什麼?另外你爲什麼使用Newtonsoft來序列化對象? – JanR

+0

重新編輯 - 如果它們是字符串,則只需引用它(請參閱上面的註釋)。但是什麼是'console.log(toDisplayNotification);'等返回? –

回答

1

試試這個

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然後將它與一個數字進行比較。