I have a very simple application. My Home controller receives a Comment object and runs its logic to determine whether a notification needs to be displayed. If the answer is yes, then it sets the following parameters in ViewBag:
ViewBag.toDisplayNotification = 1;
ViewBag.notificationTitle = "This is the title";
ViewBag.notificationId = 2;
else, it sets the parameters as follow (I randomly set everything to null so that toDisplayNotification wouldnt be 1 anymore!)
ViewBag.toDisplayNotification = null;
ViewBag.notificationTitle = null;
ViewBag.notificationId = null;
It then displays the Comment partial View in which I have:
<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>
So the issue I'm facing is that the view, regardless of the toDisplayNotification value, always displays the notification (I have tested the logic of my Home controller and know that it sets the correct values to each ViewBag property) even when the value of toDisplayNotification shouldnt be zero.
Is it possible that my ViewBag values are being changed somehow (can't be from the code since my Home controller displays the partial view directly so the values should remain unchanged in the transition) or am I missing something in my if condition?
Edit 1 - To answer some of the questions below. I am only using Newtonsoft.Json.JsonConvert.SerializeObject because someone in a different question had suggested that I use. Otherwise, I'm not a serialization expert (What I find is that unless, I serialize the property, I cannot pull non-integer values out of ViewBag into jquery/javascript).
Also, I did try replacing the toDisplayNotification line with either of the following but neither one worked:
var toDisplayNotification = @ViewBag.toDisplayNotification;
//or
var toDisplayNotification = @Html.Raw(ViewBag.toDisplayNotification);
myfunction()? (and note that you can just usevar notificationTitle = '@ViewBag.notificationTitle')console.log(toDisplayNotification);etc returning?